JavaScript实现省市联动
我们经常会遇到选择省市县的下拉框。比如我们选择了省份的话,县的下拉框会自动筛选,接下来我们就做一个这样的省市联动吧!!!
先使用一个二维数组存储省份的信息:
<script> var provinceArr=new Array(5); provinceArr[0]=new Array("南安市","泉州市","厦门市","福安市","福州市"); provinceArr[1]=new Array("郑州市","洛阳市","濮阳市","驻马店市"); provinceArr[2]=new Array("石家庄市","唐山","秦皇岛","邯郸"); provinceArr[3]=new Array("西安市","宝鸡市","延安"); provinceArr[4]=new Array("菏泽市","济南市","青岛"); </script>
定义一个onchange事件进行监听:
<select onchange="provinceChange(this)"> <!--显示省份--> <option value="0">福建省</option> <option value="1"> 河南省</option> <option value="2">河北省</option> <option value="3">陕西省</option> <option value="4">山东省</option> </select>
书写provinceChange()函数进行检验
function provinceChange(province){
console.log(provinceArr[province.value]);//province.value是获取选择的省份
}
检验的结果:
打印出的结果说明数据已存入数组中,现在需要将它显示在下一个下拉列表中
最终效果:
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>省市联动</title> 6 <script> 7 var provinceArr=new Array(5); 8 provinceArr[0]=new Array("南安市","泉州市","厦门市","福安市","福州市"); 9 provinceArr[1]=new Array("郑州市","洛阳市","濮阳市","驻马店市"); 10 provinceArr[2]=new Array("石家庄市","唐山","秦皇岛","邯郸"); 11 provinceArr[3]=new Array("西安市","宝鸡市","延安"); 12 provinceArr[4]=new Array("菏泽市","济南市","青岛"); 13 function provinceChange(province){ 14 //console.log(provinceArr[province.value]); 15 var city=document.getElementById("city"); 16 if(province.value=="-1"){ 17 city.innerHTML='<option value=\'-1\'>--请选择--</option>'; 18 return; 19 20 } 21 22 var cityArr=provinceArr[province.value]; 23 city.options.length=0; 24 for(var i=0;i<cityArr.length;i++){ 25 var cityOption=document.createElement("option");//获取元素标签option 26 cityOption.innerText=cityArr[i];//把数组里面城市的信息显示到id为city的下拉列表中 27 city.appendChild(cityOption); 28 } 29 } 30 31 </script> 32 </head> 33 <body> 34 35 <select onchange="provinceChange(this)"> 36 <!--显示省份--> 37 <option value="-1">--请选择--</option> 38 <option value="0">福建省</option> 39 <option value="1"> 河南省</option> 40 <option value="2">河北省</option> 41 <option value="3">陕西省</option> 42 <option value="4">山东省</option> 43 44 </select> 45 <select id="city"> 46 <!--显示市--> 47 <option value="-1">--请选择--</option> 48 </select> 49 </body> 50 </html>