2021-07-28 16:50

JQuery+Json数据实现省市区三级联动

wanmatea

WEB前端

(1069)

(0)

收藏

实现效果:

1.gif

js代码:

 <script type="text/javascript">
        var provinces=[
            {id:1,name:"山东省"},
            {id:2,name:"河南省"},
            {id:3,name:"四川省"},
        ];
        var citys=[
            {id:1,provinceId:1,name:"青岛市"},
            {id:2,provinceId:1,name:"烟台市"},
            {id:3,provinceId:2,name:"郑州市"},
            {id:4,provinceId:2,name:"开封市"},
            {id:5,provinceId:3,name:"成都市"},
            {id:6,provinceId:3,name:"乐山市"},
        ];
        
        var districts=[
            {id:1,cityId:1,name:"市南区"},
            {id:2,cityId:1,name:"市北区"},
             {id:3,cityId:2,name:"福山区"},
             {id:4,cityId:2,name:"莱山区"},
             {id:5,cityId:3,name:"二七区"},
             {id:6,cityId:3,name:"中原区"},
             {id:7,cityId:4,name:"龙亭区"},
             {id:8,cityId:4,name:"鼓楼区"},
             {id:9,cityId:5,name:"锦江区"},
             {id:10,cityId:5,name:"成华区"},
              {id:11,cityId:6,name:"市中区"},
             {id:12,cityId:6,name:"沙湾区"},
        ];
        
        function getCity(){
            var province=$("#province").val();
             $("#city").empty();
               $.each(citys,function(k,v){
                   if(province==v.provinceId){
                       $("#city").append("<option value='"+v.id+"'>"+v.name+"</option>");
                   }
               })
        }
        
        function getDistrict(){
            var val=$("#city").val();
                $("#district").empty();
                $.each(districts,function(k,v){
                   if(val==v.cityId){
                       $("#district").append("<option>"+v.name+"</option>");
                   }
                });
        }
        
        $(function(){
            $.each(provinces,function(k,v){
                $("#province").append("<option value='"+v.id+"'>"+v.name+"</option>");
            });
            getCity();
            getDistrict();
            
            $("#province").change(function(){
                getCity();
                getDistrict();
            });
            
            $("#city").change(function(){
                getDistrict();
            });
        });
    </script>

Html代码:

  <select id="province"></select>
    <select id="city"></select>
    <select id="district"></select>


0条评论

点击登录参与评论