设为首页 加入收藏

TOP

3.省市区,三级联动(优化版)
2019-09-17 18:36:37 】 浏览:19
Tags:省市区 三级 联动 优化

 1 <body onload="change()">
 2     <form>
 3         <select onchange="sel_one()">
 4         </select>
 5         <select onchange="sel_two()">
 6             <option>请选择所在的城市</option>
 7         </select>
 8         <select>
 9             <option>请选择所在的县区</option>
10         </select>
11     </form>
12     <script>
13         var select = document.getElementsByTagName('select');
14         var sel_1 = select[0];
15         var sel_2 = select[1];
16         var sel_3 = select[2];
17         var oAjax = new XMLHttpRequest();
18         var c = '';
19         function change() {
20             oAjax.open('GET', 'json/city.json', true);
21             oAjax.send();
22             oAjax.onreadystatechange = function () {
23                 if (oAjax.readyState == 4 && oAjax.status == 200) {
24                     c = JSON.parse(oAjax.responseText);
25                     var option_1 = '<option>请选择所在的省市</option>';
26                     for (var i = 0; i < c.city.length; i++) {
27                         option_1 += '<option>' + c.city[i].name + '</option>';
28                     }
29                     sel_1.innerHTML = option_1;
30                 }
31             }
32         }
33         function sel_one() {
34             sel_1.firstElementChild.style.display = 'none';
35             sel_3.innerHTML = '<option>请选择所在的县区</option>';
36             var index = sel_1.selectedIndex - 1;
37             if (sel_1.value == c.city[index].name) {
38                 var option_2 = '';
39                 for (var i = 0; i < c.city[index].city.length; i++) {
40                     option_2 += '<option>' + c.city[index].city[i].name + '</option>';
41                 }
42                 sel_2.innerHTML = option_2;
43             }
44             sel_two();
45         }
46         function sel_two() {
47             var index = sel_1.selectedIndex - 1;
48             var index2 = sel_2.selectedIndex;
49             if (sel_2.value == c.city[index].city[index2].name) {
50                 var option_3 = ''
51                 for (var i = 0; i < c.city[index].city[index2].area.length; i++) {
52                     option_3 += '<option>' + c.city[index].city[index2].area[i] + '</option>';
53                 }
54                 sel_3.innerHTML = option_3;
55             }
56         }
57     </script>
58 </body>

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇vue之小小动态按钮 下一篇JavaScript 转换数字为整数的方法

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目