jquery+json省市二级联动下拉

前端之家收集整理的这篇文章主要介绍了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, indexItems) {
   var proName = indexItems.name;
   $.each(indexItems.items, indexItems) {
    if (indexItems.parentNode != selectedIndex) {
     return;
    } else {
     option2 += "<option id=" + indexItems.id + ">"
       + indexItems.name + "</option>";
    }
   })
  });
  $("#selectCity").append(option2);
 };
};
$(function() {
 initPro();
});
原文链接:https://www.f2er.com/json/290701.html

猜你在找的Json相关文章