三個 <select> 分別對應「省份」、「城市」、「地區」,透過 jQuery 讀取外部 area.json,實現級聯篩選:選省份→載入城市→選城市→載入地區。支援同頁多組獨立聯動。
<div class="selectList">
<select class="province"><option>請選擇</option></select>
<select class="city"><option>請選擇</option></select>
<select class="district"><option>請選擇</option></select>
</div>
<!-- 同頁可放置多組 .selectList -->
[
{
"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":"遷西縣"}] }
]
}
]
$(function() {
$('.selectList').each(function() {
var $box = $(this);
var $prov = $box.find('.province');
var $city = $box.find('.city');
var $dist = $box.find('.district');
var data;
// 載入 JSON
$.getJSON('area.json', function(json) {
data = json;
renderProvince();
});
function renderProvince() {
var html = '<option>請選擇</option>';
$.each(data, function(i, prov) {
html += '<option value="' + prov.p + '">' + prov.p + '</option>';
});
$prov.html(html);
renderCity();
}
function renderCity() {
var html = '<option>請選擇</option>';
var idx = $prov[0].selectedIndex - 1; // 扣除「請選擇」
if (idx >= 0 && data[idx] && data[idx].c) {
$.each(data[idx].c, function(i, city) {
html += '<option value="' + city.ct + '">' + city.ct + '</option>';
});
}
$city.html(html);
renderDistrict();
}
function renderDistrict() {
var html = '<option>請選擇</option>';
var pIdx = $prov[0].selectedIndex - 1;
var cIdx = $city[0].selectedIndex - 1;
if (pIdx >= 0 && cIdx >= 0 && data[pIdx] && data[pIdx].c[cIdx] && data[pIdx].c[cIdx].d) {
$dist.show();
$.each(data[pIdx].c[cIdx].d, function(i, dist) {
html += '<option value="' + dist.dt + '">' + dist.dt + '</option>';
});
} else {
$dist.hide();
}
$dist.html(html);
}
// 事件綁定
$prov.on('change', renderCity);
$city.on('change', renderDistrict);
});
});
$.fn.cascadeSelect(options),支援自訂 JSON 路徑、欄位名、預設值、AJAX 快取。aria-label、鍵盤操作支援。AreaData 介面,編譯期捕捉欄位拼寫錯誤。