三級聯動選單常用於地址選擇、地區篩選等情境。本文使用原生 JavaScript,示範如何根據上一層選擇,動態更新下一層選項。
先準備三個 select 元素,分別代表省、市、區。
<select id="sheng"></select>
<select id="shi"></select>
<select id="qu"></select>
三級聯動的核心是嵌套資料。以下用簡化資料示範。
const cityData = [
{
name: "北京",
city: [
{
name: "北京",
area: ["東城區", "西城區", "朝陽區", "海淀區"]
}
]
},
{
name: "上海",
city: [
{
name: "上海",
area: ["黃浦區", "徐匯區", "長寧區", "靜安區"]
}
]
}
];
每次更新時,先清空原本的選項,再重新填入新的資料。
const sheng = document.getElementById("sheng");
const shi = document.getElementById("shi");
const qu = document.getElementById("qu");
function fillOptions(select, items, placeholder) {
select.innerHTML = "";
select.options[0] = new Option(placeholder, "-1");
items.forEach(function (item, index) {
select.options[select.length] = new Option(item.name || item, index);
});
}
當省份改變時,更新城市;當城市改變時,更新區域。
fillOptions(sheng, cityData, "請選擇省");
sheng.onchange = function () {
const province = cityData[sheng.selectedIndex - 1];
if (!province) {
return;
}
fillOptions(shi, province.city, "請選擇市");
fillOptions(qu, [], "請選擇區");
shi.onchange = function () {
const city = province.city[shi.selectedIndex - 1];
if (!city) {
return;
}
fillOptions(qu, city.area, "請選擇區");
};
};
實作三級聯動時,重點是資料要具備層級結構,事件要在正確時機重新綁定。若資料量很大,可改為外部 JSON 檔或 API 載入。