jquery+json省市二级联动下拉

1.html代码:
<form name="fm" id="fm">
     <select id="provice">
          <option value="-1">请选择省份</option>
     </select>
     <select id="selectCity">
          <option value="-1">请选择城市</option>
     </select>
</form>

2.定义的json数组:

[{
 "name" :"山东省",
 "id" : "001",
 "items" : [{
  "parentNode" : "山东省",
  "name" : "济南市",
  "id" : "00101"
 },
 {
  "parentNode" : "山东省",
  "name" : "青岛市",
  "id" : "00102"
 }]
},{
 "name" :"山西省",
 "id" : "002",
 "items" : [{
  "parentNode" : "山西省",
  "name" : "太原市",
  "id" : "00201"
 },
 {
  "parentNode" : "山西省",
  "name" : "大同市",
  "id" : "00202"
 }]
}]
3.javascript代码:

function initPro() {
 var option1 = '';
 $.getJSON("http://127.0.0.1:8080/json/js/citysData.json",function(jsonData) {
  $.each(jsonData, function(index, indexItems) {
   option1 += "<option id=" + indexItems.id + ">"
     + indexItems.name + "</option>";
  });
  $("#provice").append(option1);
  $("#provice").bind("change", function() {
   selectCity(jsonData);
  })
 });
 function selectCity(data) {
  var option2 = '';
  var selectedIndex = $("#provice :selected").text();
  $("#selectCity").empty();
  if($("#provice :selected").val() == -1){
   $("#selectCity").append("<option id=\"-1\">请选择城市</option>");
  }
  $.each(data, function(index, indexItems) {
   var proName = indexItems.name;
   $.each(indexItems.items, function(index, indexItems) {
    if (indexItems.parentNode != selectedIndex) {
     return;
    } else {
     option2 += "<option id=" + indexItems.id + ">"
       + indexItems.name + "</option>";
    }
   })
  });
  $("#selectCity").append(option2);
 };
};
$(function() {
 initPro();
});


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值