js三级联动练习(地址填写)
三级联动
<body> 省:<select name="" id="sheng" onChange="addShi(this)"> <!--改变调用--> <option value="">请选择</option> </select> 市:<select name="" id="shi" onChange="addQu(this)"> <option value="">请选择</option> </select> 区:<select name="" id="qu"> <option value="">请选择</option> </select> </body> <script> var data = [ ["山东省","江苏省"], [ ["山东省","济南市","青岛市","淄博市"], ["江苏省","南京市","宿迁市"], ], [ ["淄博市","张店","淄川","博山"], ["济南市","章丘","历城","历下"] ] ]; var sheng = document.getElementById('sheng'); var str = '<option>请选择</option>'; for(i = 0;i < data[0].length;i++){ str += '<option>'+data[0][i]+'</option>' } sheng.innerHTML = str; function addShi(th){ shengName=th.value; var shi=document.getElementById('shi'); var str='<option>请选择</option>'; for(i=0;i<data[1].length;i++){ if(data[1][i][0]==shengName){ for(j = 1;j < data[1][i].length;j++){ str += '<option>'+data[1][i][j]+'</option>' } break; } } shi.innerHTML=str; } function addQu(th){ shengName=th.value; var qu=document.getElementById('qu'); // 改元素 var str='<option>请选择</option>'; for(i=0;i<data[2].length;i++){ //改数组 if(data[2][i][0]==shengName){ for(j = 1;j < data[2][i].length;j++){ str += '<option>'+data[2][i][j]+'</option>' } break; } } qu.innerHTML=str; //改内容 } </script>
<body> 省:<select name="" id="sheng"> <option value="">请选择</option> </select> 市:<select name="" id="shi"> <option value="">请选择</option> </select> 区:<select name="" id="qu"> <option value="">请选择</option> </select> </body> </html> <script> var data2 = [ [1,"山东省",0], [2,"江苏省",0], [11,"济南市",1], [12,"青岛市",1], [13,"淄博市",1], [21,"南京市",2], [22,"宿迁市",2], [131,"张店",13], [132,"淄川",13], [133,"博山",13], ]; var sheng=null, shi=null, qu=null; window.onload=function(){ init(); addEvent(); } function init(){ sheng=document.getElementById('sheng'); shi=document.getElementById('shi'); qu=document.getElementById('qu'); /*initSheng()*/ changeZhi(sheng,0) } function addEvent(){ sheng.onchange = function(){ changeZhi(shi,this.value); }; shi.onchange = function(){ changeZhi(qu,this.value); }; } function changeZhi(th,code){ //我是市,我爸是请选择 var str='<option value="-1">请选择</option>';//value=""的时候 code传入this.value="" qu.innerHTML='<option value="-1">请选择</option>'; for(i=0;i<data2.length;i++){ if(data2[i][2]==code){ str+='<option value="'+data2[i][0]+'">'+data2[i][1]+'</option>'; } } th.innerHTML=str; } </script>