Javascript(8)——JSON

簡易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.jscss

/**
 * @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(截取部分,太大貼上去時間過久)html

 [ {
    "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
相關文章
相關標籤/搜索