学习javascript的时候都遇到过这样的需求,不仅是省市,还有其他的一些场景,看看关键的代码有哪些吧。
1 <head runat="server"> 2 <title>省市级联效果</title> 3 <script type="text/javascript"> 4 var cityList = [{ "province": "四川省", "city": ["成都", "内江", "绵阳", "眉山", "自贡"] }, 5 { "province": "山东省", "city": ["济南", "青岛", "德州", "淄博", "泰安", "菏泽", "临沂"] }, 6 { "province": "浙江省", "city": ["杭州", "金华", "绍兴", "温州", "衢州"] }, 7 { "province": "海南省", "city": ["海口", "三亚", "儋州", "东方", "五指山"] }, ]; 8 9 10 window.onload = function () { 11 var province = document.getElementById("province"); 12 //绑定事件 13 province.onchange = selectCity; 14 }; 15 16 function selectCity() { 17 //城市 18 var city = document.getElementById("city"); 19 //先清空数据 20 if (city != null) { 21 city.options.length = 0; 22 } 23 24 //省份 25 var province = document.getElementById("province"); 26 //获取选中省份的索引 27 var provinceSelectedIndex = province.selectedIndex; 28 //获取选中省份的项 29 var provinceSelectedOption = province.options[provinceSelectedIndex]; 30 31 //遍历城市列表 32 for (var i = 0; i < cityList.length; i++) { 33 if (cityList[i].province == provinceSelectedOption.innerText) { 34 for (var j = 0; j < cityList[i].city.length; j++) { 35 //创建节点 36 var optionNew = document.createElement("option"); 37 //为节点属性赋值 38 optionNew.innerText = cityList[i].city[j]; 39 //添加节点 40 city.appendChild(optionNew); 41 } 42 } 43 } 44 } 45 46 </script> 47 </head> 48 <body> 49 <form id="form1" runat="server"> 50 <div> 51 <select id="province" style="width: 200px;"> 52 <option selected="selected">--请选择--</option> 53 <option>四川省</option> 54 <option>山东省</option> 55 <option>浙江省</option> 56 <option>海南省</option> 57 </select> 58 <select id="city" style="width: 200px;"> 59 </select> 60 </div> 61 </form> 62 </body>
效果图:
2015年2月2日,改成代码版,原来是图片版。
锲而不舍,水滴石穿