欢迎来到刘认真的博客

It's not me that's wrong. It's the whole world

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>

 

posted @ 2019-06-26 16:38  刘认真  阅读(794)  评论(1编辑  收藏  举报