js(二) 实现省市联动(json)
通过HTML页面的city的select选取的value值,从json里面获取相对应的键值对,最后将值拼接到下拉框中
1 function x1(th) { 2 //通过传入的th的value获取相对应的citys中的json值 3 var cs=citys[th.value]; 4 var str=""; 5 //循环获取每一个值并拼接成<option></option> 6 for (var i=0;i<cs.length;i++){ 7 str+="<option>"+cs[i]+"</option>"; 8 } 9 //获取HTML页面的city 10 var city=document.getElementById("city"); 11 //将值写入界面 12 city.innerHTML=str; 13 }
源码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <select id="province" onchange="x1(this)"> <option>请选择</option> <option>福建</option> <option>江西</option> </select> <select id="city" onchange="x2(this)"> <option>请选择</option> </select> <select id="area"> <option>请选择</option> </select> <script> var citys={ "福建":["请选择","厦门","泉州","漳州"], "江西":["请选择","南昌","九江","新余"] }; var areas={ "厦门":["请选择","思明区","湖里区","同安"], "泉州":["请选择","泉州","泉州","泉州","泉州"], "南昌":["请选择","南昌","南昌","南昌","南昌"], "九江":["请选择","九江","九江","九江","九江"] } function x1(th) { var cs=citys[th.value]; var str=""; for (var i=0;i<cs.length;i++){ str+="<option>"+cs[i]+"</option>"; } var city=document.getElementById("city"); city.innerHTML=str; } function x2(th) { var aa=areas[th.value]; var str1=""; for(var i=0;i<aa.length;i++){ str1+="<option>"+aa[i]+"</option>"; } var area=document.getElementById("area"); area.innerHTML=str1; } </script> </body> </html>
作者:刘认真
-------------------------------------------
新人只求记录学习生活!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!