JS设计省、市、县的联动
最近用js写了一段省市县的联动设置,先传上来,后期会不断优化
效果图如下:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>DOM作业</title> 6 </head> 7 <!--用来演示省市县的联动--> 8 <body> 9 <select name="" id="pro"></select> 10 <select name="" id="city"></select> 11 <select name="" id="county"></select> 12 <script type="text/javascript"> 13 (function(win){ 14 win.onload=function(){ 15 16 var hgCity={name:"黄冈市",children:["蕲春区","武穴区","溪水区"]}; 17 var whCity={name:"武汉市",children:["汉口区","武昌区","汉阳区"]}; 18 var hbArray=[]; 19 hbArray.push(whCity,hgCity); 20 var hbPro={name:"湖北省",children:hbArray}; 21 22 var szCity={name:"深圳市",children:["南山区","罗湖区","盐田区"]}; 23 var dgCity={name:"东莞市",children:["凤岗县","莞城县","常平县"]}; 24 var gdArray=[]; 25 gdArray.push(szCity,dgCity); 26 var gdPro={name:"广东省",children:gdArray}; 27 28 var zjCity={name:"镇江市",children:["京口区","丹徒区","新城区"]}; 29 var njCity={name:"南京市",children:["栖霞区","江宁区","城北区"]}; 30 var jsArray=[]; 31 jsArray.push(zjCity,njCity); 32 var jsPro={name:"江苏省",children:jsArray}; 33 34 //定义省市县数组 35 var chinaArray=[]; 36 chinaArray.push(hbPro,gdPro,jsPro); 37 38 //获取省市县各级dom对象 39 var proDom = document.getElementById("pro"); 40 var cityDom =document.getElementById("city"); 41 var countyDom=document.getElementById("county"); 42 43 //初始化省 44 addDddress(chinaArray,proDom); 45 //初始化市 46 pro(); 47 //初始化县/区 48 cit(); 49 proDom.onchange=pro; 50 //省 51 function pro(){ 52 //先清空city选项 53 cityDom.innerHTML=""; 54 //当身份选项被改变时,获取省份对应的value值 55 var num = proDom.value; 56 //被选择的省份对应的市 57 var cityArray= chinaArray[num].children; 58 addDddress(cityArray,cityDom); 59 //联动县 60 cit(); 61 }; 62 //根据市选项的触发事件,自动填充县/区 63 cityDom.onchange=cit; 64 //市 65 function cit(){ 66 //每次改变时先清空上一次的值 67 countyDom.innerHTML=""; 68 //当市被改变时,自动获取对应的省,市的value 69 var num1 = proDom.value; 70 var num2 = cityDom.value; 71 //被选择的市对应的县,区 72 var countyArray = chinaArray[num1].children[num2].children; 73 addDddress(countyArray,countyDom); 74 }; 75 }; 76 //县 77 function addDddress(adrArray,dom){ 78 for(var i=0,len=adrArray.length;i<len;i++){ 79 var opt=document.createElement("option"); 80 if(adrArray[i].name){ 81 opt.innerHTML=adrArray[i].name; 82 }else{ 83 opt.innerHTML=adrArray[i]; 84 } 85 opt.value=i; 86 dom.appendChild(opt); 87 } 88 } 89 })(window) 90 91 </script> 92 </body> 93 </html>