jquery+json+ajax省市二級聯動下拉

1.html代碼:
[html]  view plain copy
  1. <form name="fm" id="fm">  
  2.      <select id="provice">  
  3.           <option value="-1">請選擇省份</option>  
  4.      </select>  
  5.      <select id="selectCity">  
  6.           <option value="-1">請選擇城市</option>  
  7.      </select>  
  8. </form>  

2.定義的json數組:javascript

[{  "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").attr("id") == -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(); });
引用來自 http://blog.csdn.net/linbooooo1987/article/details/7235205
相關文章
相關標籤/搜索