欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

3.省市区,三级联动(优化版)

程序员文章站 2022-09-30 19:35:33
1 2 3 5 8 11 12 58 ......

3.省市区,三级联动(优化版)

3.省市区,三级联动(优化版)

 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>