国内省市县地址三级联动。
地址数据存放在多维数组中,加载页面时自动载入省一级的选项,对任意选框进行选择操作后自动填充其后续select选框的所有选项option,并以第一项为默认选中项。
页面加载后选框效果如下:
选择第一项后自动填充后续项:
1 <--! HTML --> 2 <div class="container"> 3 <span class="address"> 4 <label for="province">省/直辖市:</label> 5 <select name="province" id="province" class="province"></select> 6 </span> 7 <span class="address"> 8 <label for="city">市:</label> 9 <select name="city" id="city" class="city"></select> 10 </span> 11 <span class="address"> 12 <label for="district">县/区:</label> 13 <select name="district" id="district" class="district"></select> 14 </span> 15 </div>
1 /* JS */ 2 var _selects = document.getElementsByTagName('select'), 3 address = ADDRESS_CODES, 4 _noticeOption = new Option('--请选择--'); 5 6 /* 填充选项 */ 7 function fill(_select, addr) { 8 _select.length = 0; // 清空选框中原先的option选项 9 for (var i = 0, len = addr.length; i < len; i++) { 10 _select.add(new Option(addr[i][1], addr[i][0])); 11 } 12 } 13 14 /* 填充省份 */ 15 fill(_selects[0], address); 16 _noticeOption.disabled=true; 17 _selects[0].add(_noticeOption); 18 _selects[0].selectedIndex = _selects[0].length - 1; 19 20 /* 选择省份继而填充市、区 */ 21 _selects[0].onchange = function () { 22 var i = _selects[0].selectedIndex; 23 fill(_selects[1], address[i][2]); // 填充该省下辖的市 24 fill(_selects[2], address[i][2][0][2]); // 填充该省的第一个市下辖的区 25 } 26 27 /* 选择市继而填充区 */ 28 _selects[1].onchange = function () { 29 var i = _selects[0].selectedIndex, 30 j = _selects[1].selectedIndex; 31 fill(_selects[2], address[i][2][j][2]); // 填充该市下辖的区 32 }
每一个平级的地址都独自放在一个数组的数组里,因此1级地址就得存放在2维数组里,这里是3级地址因此存放在6维数组里。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /* 部份地址 */ 2 var ADDRESS_CODES = [ 3 [ 4 "110000", 5 "北京", 6 [ 7 [ 8 "110100", 9 "北京市", 10 [ 11 [ 12 "110101", 13 "东城区" 14 ], 15 [ 16 "110102", 17 "西城区" 18 ], 19 [ 20 "110103", 21 "崇文区" 22 ], 23 [ 24 "110104", 25 "宣武区" 26 ], 27 [ 28 "110105", 29 "朝阳区" 30 ] 31 ] 32 ] 33 ] 34 ], 35 [ 36 "130000", 37 "河北省", 38 [ 39 [ 40 "130100", 41 "石家庄市", 42 [ 43 [ 44 "130102", 45 "长安区" 46 ], 47 [ 48 "130103", 49 "桥东区" 50 ], 51 [ 52 "130104", 53 "桥西区" 54 ], 55 [ 56 "130105", 57 "新华区" 58 ], 59 [ 60 "130107", 61 "井陉矿区" 62 ] 63 64 ] 65 ], 66 [ 67 "130200", 68 "唐山市", 69 [ 70 [ 71 "130202", 72 "路南区" 73 ], 74 [ 75 "130203", 76 "路北区" 77 ], 78 [ 79 "130204", 80 "古冶区" 81 ] 82 83 ] 84 ] 85 ] 86 ] 87 ]