省市縣三級聯動 javascript 原生實現例項
阿新 • • 發佈:2019-01-04
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>三級 省市區</title> </head> <body> <select id="pro"></select> <select id="city"></select> <select id="area"></select> <script> var arr1=['安徽','河北','浙江'];//定義省的陣列arr1 var arr2=[['合肥','滁州','蕪湖'],['秦皇島','唐山','邯鄲'],['杭州','麗水','金華']]; //定義市的陣列arr2 var arr3=[[['合肥一區','合肥二區','合肥三區'],['滁州一區','滁州二區','滁州三區'], ['蕪湖一區','蕪湖二區','蕪湖三區']],[['秦皇島一區','秦皇島二區','秦皇島三區'], ['唐山一區','唐山二區','唐山三區'],['邯鄲一區','邯鄲二區','邯鄲三區']], [['杭州一區','杭州二區','杭州三區'],['麗水一區','麗水二區','麗水三區'], ['金華一區','金華二區','金華三區']]];//定義區的陣列arr3 var obj1=document.getElementById("pro");//獲取省的select目標 var obj2=document.getElementById("city");//獲取市的select目標 var obj3=document.getElementById("area");//獲取區的select目標 //設定預設顯示的省開始 var str1=""; for(var x=0;x<arr1.length;x++){ str1=str1+"<option>"+arr1[x]+"</option>"; } obj1.innerHTML=str1; //設定預設顯示的省結束 //設定預設顯示的市開始 var str2=""; for(vary=0;y<arr2[1].length;y++ ){ str2=str2+"<option>"+arr2[0][y]+"</option>"; } obj2.innerHTML=str2; //設定預設顯示的市結束 //設定預設顯示的區開始 var str3=""; for(var z=0;z<arr3[1].length;z++){ str3=str3+"<option>"+arr3[0][0][z]+"</option>"; } obj3.innerHTML=str3; //設定預設顯示的區結束 obj1.onchange=function(){ var inst1=this.selectedIndex; varstr4=""; for(var m=0;m<arr2[inst1].length;m++){ str4=str4+"<option>"+arr2[inst1][m]+"</option>"; } obj2.innerHTML=str4; varstr5=""; for(var n=0;n<arr3[inst1][0].length;n++){ str5=str5+"<option>"+arr3[inst1][0][n]+"</option>"; } obj3.innerHTML=str5; obj2.onchange=function(){ var inst2=this.selectedIndex; varstr6=""; for(var n=0;n<arr3[inst1][inst2].length;n++){ str6=str6+"<option>"+arr3[inst1][inst2][n]+"</option>"; } obj3.innerHTML=str6; } } </script> </body> </html>