javascript实现下拉列表二级联动
效果展示
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>标题</title> 6 <script type="text/javascript"> 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 14 15 function provinceChange(province) { 16 var city = document.getElementById("city"); 17 if (province.value=="-1"){ //判断当一级选项选择 请选择 时,二级选项也为 请选择 18 city.innerHTML="<option value=\"-1\">-请选择-</option>"; 19 return; //加return表示如果一级选择 请选择 选项,二级选项不用遍历 20 } 21 city.options.length=0; //设置二级选项的option标签数量为0,每次一级选项改变时,二级选项内容先清空再添加 22 var cityArr=provinceArr[province.value]; 23 for(var i=0;i<cityArr.length;i++){ 24 var cityOption = document.createElement("option"); //* <option></option> 25 cityOption.innerText=cityArr[i]; 26 city.appendChild(cityOption); //* appendChild 27 } 28 } 29 </script> 30 </head> 31 <body> 32 <select onchange="provinceChange(this)"> 33 <option value="-1">-请选择-</option> 34 <option value="0">北京市</option> 35 <option value="1">河南省</option> 36 <option value="2">河北省</option> 37 <option value="3">陕西省</option> 38 <option value="4">山东省</option> 39 </select> 40 <select id="city"> 41 <option value="-1">-请选择-</option> 42 </select> 43 </body> 44 </html>