简易json数据三级联动下拉框(JQuery实现)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="../vendor/bootstrap-4.3.1-dist/css/bootstrap.min.css">
    <script src="../vendor/jquery-3.4.1.js"></script>
    <script src="../vendor/bootstrap-4.3.1-dist/js/bootstrap.min.js"></script>
    <script src="../base.js"></script>
    <script src="./linkage.js"></script>
    <script>
        $(function(){
            init();
        })
    </script>
</head>
<body>
    <div class="container">
        <h1 class=" my-5">三级联动</h1>
       <div class="form-group row">
            <div class="form-group col-md-2">
                    <label for="provinces" >选择省份</label>
                    <select id="provinces" class="form-control">
                    </select>
            </div>
            <div class="form-group col-md-2">
                <label for="cities">选择城市</label>
                <select id="cities" class="form-control">
                </select>
            </div>
            <div class="form-group col-md-2">
                    <label for="counties">选择县区</label>
                    <select id="counties" class="form-control">
                    </select>
            </div>
       </div>
    </div>
</body>
</html>

 

linkage.js

/**
 * @author Dev
 * Alter-Date:  2019-10-13
 *  完成功能
 * Alter-Date:  2019-10-14
 *  空数据处理
 * 
 * warning:
 * 如果不是预期的JSON格式将会出错
 */

/**
 * 初始化
 */
function init(){
    /**
     * 缓存select对象
     */
    var provinceSelect = $("#provinces"),citySelect = $("#cities"),countySelect = $("#counties");
    /**
     * 获取三级联动JSON数据
     */
    var linkageJSON = null;
    $.getJSON('json/cities.json',function(data){
        linkageJSON = data;
        // 页面初始化并获取到JSON数据后显示下拉框
        setProvinces(provinceSelect,linkageJSON);
        setCities(provinceSelect,citySelect,linkageJSON);
        setCounties(provinceSelect,citySelect,countySelect,linkageJSON);
    });
    
    // 添加省份下拉框事件
    provinceSelect.change(function(){
        setCities(provinceSelect,citySelect,linkageJSON);
        setCounties(provinceSelect,citySelect,countySelect,linkageJSON);
    }); 
    // 添加城市下拉框事件
    citySelect.change(function(){
        setCounties(provinceSelect,citySelect,countySelect,linkageJSON);
    })
}

/**
 * 设置省份信息
 * @param {} provinceSelect  省份下拉框对象
 * @param {} linkageJSON JSON数据
 */
function setProvinces(provinceSelect,linkageJSON){
    setInfo(provinceSelect,linkageJSON);
}

/**
 * set the cities
 * @param {*} provinceSelect 省份下拉框对象
 * @param {*} citySelect 城市下拉框对象
 * @param {*} linkageJSON 
 */
function setCities(provinceSelect,citySelect,linkageJSON){
    var provinceIdx = provinceSelect[0].selectedIndex;
    /**
     * 若能获取省份下标
     * 通过这个下标获取JSON数据的对应省份,并获取它的cityList,设置到城市下拉框中
     */
    if(provinceIdx != -1){
        setInfo(citySelect,linkageJSON[provinceIdx].cityList);
    }else{
        console.log('No province information');
        //无省份信息,将城市下拉框设为空
        setInfo(citySelect,[]);
    }
}

/**
 * 设置指定省份下的指定城市的县区信息
 * @param {*} provinceSelect 省份select对象
 * @param {*} citySelect 市区select对象
 * @param {*} countySelect 县区select对象
 * @param {*} linkageJSON JSON数据
 */
function setCounties(provinceSelect,citySelect,countySelect,linkageJSON){
    var provinceIdx = provinceSelect[0].selectedIndex;
    var cityIdx = citySelect[0].selectedIndex;
    /**
     * 若能省份和城市下标,设置县区信息
     */
    if(provinceIdx != -1 && cityIdx != -1){
        setInfo(countySelect,linkageJSON[provinceIdx].cityList[cityIdx].areaList);
    } else {
        console.log('No city information');
        setInfo(countySelect,[]);
    }
   
}

/**
 * 将给定数组元素array的数据,设置为对应select元素对象obj的下拉框中
 * @param {*} obj 对应的select元素对象
 * @param {*} array 对应JSON数组中的信息
 */
function setInfo(obj, array){
    if(!array){
        console.log('array data is not available, maybe null or undefined');
        array = [];
    }
    var string = '';
    array.forEach(function(item,idx){
        string += '<option value="'+item.code+'">'+item.name+'</option>';
    })
    obj.html(string);
}

 

function print(log){
    console.log(log);
}
function getRandom(start, end){
    if(!(start<=end)) return -1;
    return Math.floor(start + Math.random()*(1 + end - start));
}
base.js

 

cities.json(截取部分,太大贴上去时间太久)

 [ {
    "code": "110000",
    "name": "北京市",
    "cityList": [
      {
        "code": "110000",
        "name": "北京市",
        "areaList": [
          {
            "code": "110101",
            "name": "东城区"
          },
          {
            "code": "110102",
            "name": "西城区"
          },
          {
            "code": "110105",
            "name": "朝阳区"
          },
          {
            "code": "110106",
            "name": "丰台区"
          },
          {
            "code": "110107",
            "name": "石景山区"
          },
          {
            "code": "110108",
            "name": "海淀区"
          },
          {
            "code": "110109",
            "name": "门头沟区"
          },
          {
            "code": "110111",
            "name": "房山区"
          },
          {
            "code": "110112",
            "name": "通州区"
          },
          {
            "code": "110113",
            "name": "顺义区"
          },
          {
            "code": "110114",
            "name": "昌平区"
          },
          {
            "code": "110115",
            "name": "大兴区"
          },
          {
            "code": "110116",
            "name": "怀柔区"
          },
          {
            "code": "110117",
            "name": "平谷区"
          },
          {
            "code": "110118",
            "name": "密云区"
          },
          {
            "code": "110119",
            "name": "延庆区"
          }
        ]
      }
    ]
  },
  {
    "code": "120000",
    "name": "天津市",
    "cityList": [
      {
        "code": "120000",
        "name": "天津市",
        "areaList": [
          {
            "code": "120101",
            "name": "和平区"
          },
          {
            "code": "120102",
            "name": "河东区"
          },
          {
            "code": "120103",
            "name": "河西区"
          },
          {
            "code": "120104",
            "name": "南开区"
          },
          {
            "code": "120105",
            "name": "河北区"
          },
          {
            "code": "120106",
            "name": "红桥区"
          },
          {
            "code": "120110",
            "name": "东丽区"
          },
          {
            "code": "120111",
            "name": "西青区"
          },
          {
            "code": "120112",
            "name": "津南区"
          },
          {
            "code": "120113",
            "name": "北辰区"
          },
          {
            "code": "120114",
            "name": "武清区"
          },
          {
            "code": "120115",
            "name": "宝坻区"
          },
          {
            "code": "120116",
            "name": "滨海新区"
          },
          {
            "code": "120117",
            "name": "宁河区"
          },
          {
            "code": "120118",
            "name": "静海区"
          },
          {
            "code": "120119",
            "name": "蓟州区"
          }
        ]
      }
    ]
  }
]
cities.json