1 <!DOCTYPE html>
2 <html lang="en">
3
4 <head>
5 <meta charset="UTF-8">
6 <meta http-equiv="X-UA-Compatible" content="IE=edge">
7 <meta name="viewport" content="width=device-width, initial-scale=1.0">
8 <title>Document</title>
9 </head>
10
11 <style>
12 .box {
13 position: absolute;
14 top: 100px;
15 left: 50%;
16 transform: translateX(-50%);
17
18 }
19 select{
20 width: 200px;
21 height: 38px;
22
23 }
24 </style>
25 <script src="./data.js"></script>
26
27 <body>
28 <div class="box">
29 <select id="province">
30 <!-- <option>山东</option>
31 <option>河南</option>
32 <option>浙江</option>
33 <option>广东</option>
34 <option>云南</option> -->
35 </select>
36
37 <select id="city">
38 <!-- <option>济南</option>
39 <option>青岛</option>
40 <option>济宁</option>
41 <option>淄博</option>
42 <option>烟台</option> -->
43 </select>
44
45 <select id="area">
46 <!-- <option>历下区</option>
47 <option>惠济区</option> -->
48
49 </select>
50 </div>
51
52 <script>
53 console.log(data);
54
55 // 获取省市区dom元素
56 var province = document.getElementById('province');
57 var city = document.getElementById('city');
58 var area = document.getElementById('area');
59
60
61 // 渲染省份
62 render(province,data)
63
64 // 给省份绑定点击事件
65 province.addEventListener('click',function(){
66 // 获取当前你点击的哪个省下标
67 // -1的原因是因为新增了一项请选择 (会出现下标混乱,重置区县)
68 var pIndex =province.selectedIndex-1;
69 console.log(pIndex);
70 // 获取地级市
71 // data[ city[pIndex].cityList]
72 console.log(data[pIndex].cityList);
73 // console.log(pIndex);
74
75 // 渲染地级市
76 render(city,data[pIndex].cityList)
77 })
78
79 // 给地级市绑定点击事件
80 city.addEventListener('click',function(){
81
82 // 先获取省份下标
83 var pIndex =province.selectedIndex-1
84 // 获取你点击的那个地级市下标
85 // -1的原因是因为新增了一项请选择
86 var cIndex =city.selectedIndex-1;
87
88 console.log(cIndex);
89 // 当点击了地级市之后获取当前地级市
90 // data[province.selectedIndex].cityList[cIndex]
91 console.log( data[pIndex].cityList[cIndex]);
92 // 当前城市的区县
93 // data[province.selectedIndex].cityList[cIndex].areaList;
94 var areaList= data[pIndex].cityList[cIndex].areaList;
95 console.log( areaList,'区县');
96
97 // 渲染当前区县
98 render(area, areaList)
99
100 })
101
102 // 封装省市区渲染方法 函数四要素:参数、返回值、功能、何时调用
103 function render(ele,list) {
104 // 根据·data数据给省渲染
105 ele.innerHTML =`<option >请选择</option>`+ list.map(function (item) {
106
107 return `<option >${item.name || item}</option>`;
108 });
109
110 }
111
112 </script>
113
114 </body>
115
116 </html>