在網頁開發中,常常需要實現省市縣級聯選擇功能。使用jQuery Ajax可以輕松實現這一功能。
首先,需準備好省市縣的數據。可以使用Json格式存儲,例如:
[
{
"province": "浙江省",
"cities": [
{
"city": "杭州市",
"counties": [
"西湖區",
"拱墅區",
"上城區",
"下城區"
]
},
{
"city": "溫州市",
"counties": [
"鹿城區",
"龍灣區",
"甌海區",
"洞頭區"
]
}
]
},
{
"province": "江蘇省",
"cities": [
{
"city": "南京市",
"counties": [
"玄武區",
"白下區",
"鼓樓區",
"建鄴區"
]
},
{
"city": "蘇州市",
"counties": [
"姑蘇區",
"高新區",
"工業園區",
"虎丘區"
]
}
]
}
]
然后,使用jQuery Ajax請求該數據:
$.ajax({
type: "GET",
url: "data.json",
dataType: "json",
success: function (data) {
//省份數據處理
var provinceHtml = "";
for (var i = 0; i < data.length; i++) {
provinceHtml += "<option>" + data[i].province + "</option>"
}
$("#province").append(provinceHtml);
//城市數據處理
$("#province").change(function () {
var selectedProvince = $(this).val();
var cities = data.find(function (item) {
return item.province === selectedProvince;
}).cities;
var citiesHtml = "";
for (var i = 0; i < cities.length; i++) {
citiesHtml += "<option>" + cities[i].city + "</option>"
}
$("#city").html(citiesHtml);
//縣區數據處理
$("#city").change(function () {
var selectedCity = $(this).val();
var counties = cities.find(function (item) {
return item.city === selectedCity;
}).counties;
var countiesHtml = "";
for (var i = 0; i < counties.length; i++) {
countiesHtml += "<option>" + counties[i] + "</option>"
}
$("#county").html(countiesHtml);
});
});
}
});
最后,在HTML中添加select元素:
<select id="province"></select>
<select id="city"></select>
<select id="county"></select>
通過以上代碼和HTML,即可實現簡單的省市縣級聯選擇。