下拉列表框三级联动

时间:2022-12-26 10:08:39

Web页面实现三级联动
最近项目里面有一个功能需要使用三级联动来实现,但是项目中又没有很好的 demo 来实现这个功能,于是乎自己手敲了一个简单的三级联动的代码,记录一下。时间仓促,代码中还有很多地方可以优化。

 <div class="row">
     <div class="col-sm-6">
         <select id="province" name="province"  class="chosen-select form-control m-b" tabindex="1">
             <option>===请选择===</option>
         </select>
     </div>
     <span style="color: red; font-size: 23px">*</span>
     <small>[ 省 ]</small>
 </div>
 <br>

 <div class="row">
     <div class="col-sm-6">
         <select id="city" name="city"  class="chosen-select form-control m-b" tabindex="1">
             <option>===请选择===</option>
         </select>
     </div>
     <span style="color: red; font-size: 23px">*</span>
     <small>[ 市 ]</small>
 </div>
 <br>

 <div class="row">
     <div class="col-sm-6">
         <select id="district" name="district" class="chosen-select form-control m-b" tabindex="1">
             <option>===请选择===</option>
         </select>
     </div>
     <span style="color: red; font-size: 23px">*</span>
     <small>[ 区 ]</small>
 </div>
 <br>
<script type="text/javascript">

    var province_id = '1000';
    var city_id ='1100';
    var district_id = '1110';

    // 初始化省
    initAddress();

    function initAddress() {
        $.ajax({
            type:'GET',
            url:'${contextPath}/test/get_province',
            success:function(data) {
                $.each(data.data, function(key, value) {
                    $("#province").append("<option value='"+key+"'>" + value + "</option>");
                });

                //回显数据
                if (province_id != null) {
                    $("#province option").each(function () {
                        if ($(this).val() == province_id){
                            $(this).attr("selected", true);
                            getCity(province_id)
                        }
                    })
                }
            }
        });
    }

    function getCity(province_id) {
        $("#city").find("option").remove();
        $.ajax({
            type:'GET',
            url:'${contextPath}/test/get_city',
            data:{
                province_id:province_id
            },
            success:function(data) {
                $("#city").append("<option value=''>" + '===请选择===' + "</option>");
                $.each(data.data, function(key, value) {
                    $("#city").append("<option value='"+key+"'>" + value + "</option>");
                });

                //回显数据
                if (city_id != null) {
                    $("#city option").each(function () {
                        if ($(this).val() == city_id){
                            $(this).attr("selected", true);
                            getDistrict(city_id)
                        }
                    })
                }
            }
        });
    }

    function getDistrict(city_id) {
        $("#district").find("option").remove();
        $.ajax({
            type:'GET',
            url:'${contextPath}/test/get_district',
            data:{
                city_id:city_id
            },
            success:function(data) {
                $("#district").append("<option value=''>" + '===请选择===' + "</option>");
                $.each(data.data, function(key, value) {
                    $("#district").append("<option value='"+key+"'>" + value + "</option>");
                });

                //回显数据
                if (district_id != null) {
                    $("#district option").each(function () {
                        if ($(this).val() == district_id)
                            $(this).attr("selected", true);
                    })
                }
            }
        });
    }

    //change事件监听province改变,获取该省份下面的市
    $("#province").change(function() {
        var province_id = $("#province option:selected").val();
        getCity(province_id);
        getDistrict(null);
    });

    //change事件监听city改变,获取该省份下面的市
    $("#city").change(function() {
        var city_id = $("#city option:selected").val();
        getDistrict(city_id);
    });

</script>

Java 后台代码

    /**
     * 获取省
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_province")
    public JSONResultDTO get_province() {
        Map<String, String> provinceMap = new HashMap<>(4);
        provinceMap.put("1000","江苏省");
        provinceMap.put("2000","山东省");

        return createSuccessResult(provinceMap);
    }

    /**
     * 获取市
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_city")
    public JSONResultDTO get_city(String province_id) {
        Map<String, String> provinceMap = new HashMap<>(4);

        if (province_id.equals("1000")) {
            provinceMap.put("1100", "南京市");
            provinceMap.put("1200", "无锡市");
        }

        if (province_id.equals("2000")) {
            provinceMap.put("2100", "济南市");
            provinceMap.put("2200", "青岛市");
        }

        return createSuccessResult(provinceMap);
    }

    /**
     * 获取区
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_district")
    public JSONResultDTO get_district(String city_id) {
        Map<String, String> cityMap = new HashMap<>(8);

        if (city_id.equals("1100")) {
            cityMap.put("1110", "浦口区");
            cityMap.put("1120", "鼓楼区");
        }

        if (city_id.equals("1200")) {
            cityMap.put("1210", "崇安区");
            cityMap.put("1220", "滨湖区");
        }

        if (city_id.equals("2100")) {
            cityMap.put("2110", "历下区");
            cityMap.put("2120", "市中区");
        }

        if (city_id.equals("2200")) {
            cityMap.put("2210", "市南区");
            cityMap.put("2220", "市北区");
        }

        return createSuccessResult(cityMap);
    }

三级联动的关键代码就是这几行:

    $.each(data.data, function(key, value) {
        $("#province").append("<option value='"+key+"'>" + value + "</option>");
    });

    //回显数据
    if (province_id != null) {
        $("#province option").each(function () {
            if ($(this).val() == province_id){
                $(this).attr("selected", true);
                getCity(province_id)
            }
        })
    }

循环后台的数据,append 到对应的下拉列表框中,然后下面循环下拉数据和变量比较,用于编辑页面的数据回显。对比后将其设置为 selected 并且调用下一级的查询。

本文由个人 hexo 博客 co2fe.com 迁移
date: 2018-10-26 09:44:19