<!DOCTYPE html> <html> <head> <meta charset=gbk /> <title>selectList</title> <style type="text/css"> *{margin:0;padding:0;} .selectList{width:200px;margin:50px auto;} </style> <script type="text/javascript" src="jquery1.7.1.js"></script> </head> <body> <div class="selectList"> <select class="province"> <option>請選擇</option> </select> <select class="city"> <option>請選擇</option> </select> <select class="district"> <option>請選擇</option> </select> </div> <div class="selectList"> <select class="province"> <option>請選擇</option> </select> <select class="city"> <option>請選擇</option> </select> <select class="district"> <option>請選擇</option> </select> </div> <script type="text/javascript"> $(function(){ $(".selectList").each(function(){ var url = "area.json"; var areaJson; var temp_html; var oProvince = $(this).find(".province"); var oCity = $(this).find(".city"); var oDistrict = $(this).find(".district"); //初始化省 var province = function(){ $.each(areaJson,function(i,province){ temp_html+="<option value='"+province.p+"'>"+province.p+"</option>"; }); oProvince.html(temp_html); city(); }; //賦值市 var city = function(){ temp_html = ""; var n = oProvince.get(0).selectedIndex; $.each(areaJson[n].c,function(i,city){ temp_html+="<option value='"+city.ct+"'>"+city.ct+"</option>"; }); oCity.html(temp_html); district(); }; //賦值縣 var district = function(){ temp_html = ""; var m = oProvince.get(0).selectedIndex; var n = oCity.get(0).selectedIndex; if(typeof(areaJson[m].c[n].d) == "undefined"){ oDistrict.css("display","none"); }else{ oDistrict.css("display","inline"); $.each(areaJson[m].c[n].d,function(i,district){ temp_html+="<option value='"+district.dt+"'>"+district.dt+"</option>"; }); oDistrict.html(temp_html); }; }; //選擇省改變市 oProvince.change(function(){ city(); }); //選擇市改變縣 oCity.change(function(){ district(); }); //獲取json數據 $.getJSON(url,function(data){ areaJson = data; province(); }); }); }); </script> </body> </html>
[ {"p":"江西省", "c":[ {"ct":"南昌市", "d":[ {"dt":"西湖區"}, {"dt":"東湖區"}, {"dt":"高新區"} ]}, {"ct":"贛州市", "d":[ {"dt":"瑞金縣"}, {"dt":"南豐縣"}, {"dt":"全南縣"} ]} ]}, {"p":"北京", "c":[ {"ct":"東城區"}, {"ct":"西城區"} ]}, {"p":"河北省", "c":[ {"ct":"石家莊", "d":[ {"dt":"長安區"}, {"dt":"橋東區"}, {"dt":"橋西區"} ]}, {"ct":"唐山市", "d":[ {"dt":"灤南縣"}, {"dt":"樂亭縣"}, {"dt":"遷西縣"} ]} ]} ]