jquery json三級(jí)聯(lián)動(dòng)在網(wǎng)頁(yè)中應(yīng)用廣泛,可以通過(guò)以下代碼實(shí)現(xiàn):
$(function(){ // 省市區(qū)數(shù)據(jù) var address_data = [ {"name":"北京市","city":[ {"name":"北京市","area":[ "東城區(qū)", "西城區(qū)", "崇文區(qū)", "宣武區(qū)", "朝陽(yáng)區(qū)", "豐臺(tái)區(qū)", "石景山區(qū)", "海淀區(qū)", "門頭溝區(qū)", "房山區(qū)", "通州區(qū)", "順義區(qū)", "昌平區(qū)", "大興區(qū)", "懷柔區(qū)", "平谷區(qū)", "延慶縣", "密云縣" ]} ]}, {"name":"上海市","city":[ {"name":"上海市","area":[ "寶山區(qū)", "嘉定區(qū)", "浦東新區(qū)", "金山區(qū)", "青浦區(qū)", "松江區(qū)", "閔行區(qū)", "徐匯區(qū)", "長(zhǎng)寧區(qū)", "黃浦區(qū)", "普陀區(qū)", "閘北區(qū)", "虹口區(qū)", "楊浦區(qū)", "奉賢區(qū)", "崇明縣", "南匯區(qū)" ]} ]}, {"name":"廣東省","city":[ {"name":"廣州市","area":[ "天河區(qū)", "越秀區(qū)", "海珠區(qū)", "荔灣區(qū)", "白云區(qū)", "番禺區(qū)", "黃埔區(qū)", "花都區(qū)", "從化區(qū)", "增城區(qū)" ]}, {"name":"深圳市","area":[ "福田區(qū)", "羅湖區(qū)", "寶安區(qū)", "龍崗區(qū)", "龍華新區(qū)", "南山區(qū)", "鹽田區(qū)" ]} ]} ]; // 獲取省份數(shù)據(jù) function getProvince(){ var province_list = ""; $.each(address_data, function(index, province){ province_list += ""; }); $("#province").html(province_list); } // 獲取市區(qū)數(shù)據(jù) function getCity(province_name){ var city_list = ""; $.each(address_data, function(index, province){ if(province.name == province_name){ $.each(province.city, function(index, city){ city_list += ""; }); } }); $("#city").html(city_list); } // 獲取區(qū)縣數(shù)據(jù) function getArea(province_name, city_name){ var area_list = ""; $.each(address_data, function(index, province){ if(province.name == province_name){ $.each(province.city, function(index, city){ if(city.name == city_name){ $.each(city.area, function(index, area){ area_list += ""; }); } }); } }); $("#area").html(area_list); } // 初始化 getProvince(); // 選擇省份 $("#province").change(function(){ var province_name = $("#province option:selected").val(); getCity(province_name); $("#area").html(""); }); // 選擇城市 $("#city").change(function(){ var province_name = $("#province option:selected").val(); var city_name = $("#city option:selected").val(); getArea(province_name, city_name); }); });
以上代碼中,address_data數(shù)組存儲(chǔ)了省、市、區(qū)三級(jí)聯(lián)動(dòng)數(shù)據(jù),getProvince()函數(shù)用來(lái)獲取省份數(shù)據(jù)并渲染到省份下拉框中,getCity()函數(shù)用來(lái)根據(jù)選擇的省份獲取對(duì)應(yīng)的市區(qū)數(shù)據(jù)并渲染到市區(qū)下拉框中,getArea()函數(shù)用來(lái)根據(jù)選擇的省份和城市獲取對(duì)應(yīng)的區(qū)縣數(shù)據(jù)并渲染到區(qū)縣下拉框中。通過(guò)給省份下拉框和城市下拉框綁定change事件,在選擇對(duì)應(yīng)選項(xiàng)時(shí)調(diào)用以上函數(shù)可以實(shí)現(xiàn)省、市、區(qū)三級(jí)聯(lián)動(dòng)效果。