三級聯動是表單裡的常客:選了省份,城市清單跟著更新;選了城市,區縣再進一步收斂。這篇用純 JavaScript 實作一個可重複使用的元件,並支援兩種呈現模式。

模式一(type: 1)一次顯示省、市、縣三個下拉選單,並可為三者設定不同的預設提示文字,也能讓它們共用同一組預設值。模式二(type: 2)採逐層顯示:初始只有省份可見,選完省份才出現城市,選完城市才出現區縣,畫面更清爽。
兩種模式都可以透過 changeend 回呼取得目前選取的省、市、縣,方便接續做其他處理。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>城市三級聯動</title>
<style type="text/css">
* { padding: 0; margin: 0; }
html, body { height: 100%; width: 100%; position: relative; font-size: 14px; }
.city { margin: 20px 200px; }
.selectbox { height: 50px; width: 500px; background: #999; }
.selectbox select {
height: 30px; width: 120px; margin-right: 10px;
border: 1px solid #999; line-height: 30px;
}
</style>
</head>
<body>
<div class="city">
<p>效果一:省市縣設定不同預設項</p>
<div id="selectbox1" class="selectbox"></div>
</div>
<div class="city">
<p>效果一:省市縣設定相同預設項</p>
<div id="selectbox2" class="selectbox"></div>
</div>
<div class="city">
<p>效果二:逐層顯示,選完上一層才出現下一層</p>
<div id="selectbox3" class="selectbox"></div>
</div>
<script type="text/javascript">
window.onload = function () {
// 效果一
new TbdCityChoice({
id: "selectbox1", type: 1,
province: "請選擇省份", city: "請選擇市", town: "請選擇縣",
names: ["name1", "name2", "name3"],
changeend: function (p, c, t) { }
}).init();
// 效果一,三層共用相同預設值
new TbdCityChoice({
id: "selectbox2", type: 1,
province: "請選擇", city: "請選擇", town: "請選擇",
names: ["name4", "name5", "name6"],
changeend: function (p, c, t) {
alert("省:" + p + " 市:" + c + " 縣:" + t);
// 在此依返回值做其他處理
}
}).init();
// 效果二
new TbdCityChoice({
id: "selectbox3", type: 2,
province: "請選擇省份", city: "請選擇市", town: "請選擇縣",
names: ["name7", "name8", "name9"],
changeend: function (p, c, t) { }
}).init();
};
</script>
元件用建構函式撰寫,把設定封裝在 args 中,對外只暴露 init() 與 changeend 回呼:
/*
args.id 根容器 id
args.type 1 = 三層同時顯示;2 = 逐層顯示
args.province 省份預設文字
args.city 城市預設文字
args.town 區縣預設文字
args.names [省, 市, 縣] 三個 select 的 name
args.changeend 變更後的回呼,參數為 (province, city, town)
*/
function TbdCityChoice(args) {
this.rootele = document.getElementById(args.id);
this.type = args.type;
this.province = args.province;
this.city = args.city;
this.town = args.town;
this.nameprovince = args.names[0];
this.namecity = args.names[1];
this.nametown = args.names[2];
this.changeend = args.changeend;
this.aid = null; // 省份索引
this.bid = null; // 城市索引
var that = this;
this.onelen = mapCityChoice.length;
this.init = function () {
this.appe();
this.appendone();
this.appendtwo(this.aid);
this.appendthree(this.bid);
this.addevent();
};
// 建立三個 select 與預設 option
this.appe = function () {
this.aele = document.createElement("select");
this.aele.name = this.nameprovince;
this.rootele.appendChild(this.aele);
var tso = document.createElement("option");
tso.innerHTML = this.province;
tso.value = this.province;
tso.selected = true;
this.aele.appendChild(tso);
this.bele = document.createElement("select");
this.bele.name = this.namecity;
this.rootele.appendChild(this.bele);
this.cele = document.createElement("select");
this.cele.name = this.nametown;
this.rootele.appendChild(this.cele);
if (this.type == 2) {
this.bele.style.visibility = "hidden";
this.cele.style.visibility = "hidden";
}
};
// 填充省份
this.appendone = function () {
for (var i = 0; i < this.onelen; i++) {
var opo = document.createElement("option");
opo.innerHTML = mapCityChoice[i].name;
opo.value = mapCityChoice[i].name;
this.aele.appendChild(opo);
}
};
// 填充城市
this.appendtwo = function () {
var tso = document.createElement("option");
tso.innerHTML = this.city;
tso.value = this.city;
tso.selected = true;
this.bele.appendChild(tso);
if (this.aid != null) {
var arr = mapCityChoice[this.aid].city;
for (var j = 0; j < arr.length; j++) {
var opo = document.createElement("option");
opo.innerHTML = arr[j].name;
opo.value = arr[j].name;
this.bele.appendChild(opo);
}
}
};
// 填充區縣
this.appendthree = function () {
var tso = document.createElement("option");
tso.innerHTML = this.town;
tso.value = this.town;
tso.selected = true;
this.cele.appendChild(tso);
if (this.bid != null) {
var arr = mapCityChoice[this.aid].city[this.bid].area;
for (var j = 0; j < arr.length; j++) {
var opo = document.createElement("option");
opo.innerHTML = arr[j];
opo.value = arr[j];
this.cele.appendChild(opo);
}
}
};
// 事件綁定
this.addevent = function () {
this.aele.onchange = function () {
if (this.value != that.province) {
that.aid = that.searchcity(this.value);
if (that.type == 2) {
that.bele.style.visibility = "visible";
that.cele.style.visibility = "hidden";
}
} else {
that.aid = null;
if (that.type == 2) {
that.bele.style.visibility = "hidden";
that.cele.style.visibility = "hidden";
}
}
that.bele.innerHTML = "";
that.appendtwo();
that.bid = null;
that.cele.innerHTML = "";
that.appendthree();
that.eventchange();
};
this.bele.onchange = function () {
if (this.value != that.city) {
that.bid = that.searcharea(this.value);
if (that.type == 2) { that.cele.style.visibility = "visible"; }
} else {
that.bid = null;
if (that.type == 2) { that.cele.style.visibility = "hidden"; }
}
that.cele.innerHTML = "";
that.appendthree();
that.eventchange();
};
this.cele.onchange = function () { that.eventchange(); };
};
this.searchcity = function (oneval) {
for (var i = 0; i < mapCityChoice.length; i++) {
if (mapCityChoice[i].name == oneval) { return i; }
}
};
this.searcharea = function (twoval) {
for (var i = 0; i < mapCityChoice[that.aid].city.length; i++) {
if (mapCityChoice[that.aid].city[i].name == twoval) { return i; }
}
};
this.eventchange = function () {
var resultp = (that.aele.value == that.province) ? false : that.aele.value;
var resultc = (that.bele.value == that.city) ? false : that.bele.value;
var resultt = (that.cele.value == that.town) ? false : that.cele.value;
that.changeend(resultp, resultc, resultt);
};
}
</script>
行政區資料放在一個名為 mapCityChoice 的陣列中,結構是「省 → city 陣列 → area 陣列」的三層嵌套:
var mapCityChoice = [
{
"name": "北京",
"city": [{
"name": "北京",
"area": ["東城區", "西城區", "朝陽區", "海淀區", "通州區", "昌平區"]
}]
},
{
"name": "河北",
"city": [
{ "name": "石家莊", "area": ["長安區", "橋東區", "橋西區", "新華區", "正定縣"] },
{ "name": "唐山", "area": ["路南區", "路北區", "古冶區", "開平區", "豐潤區"] }
]
}
// 其餘省市資料依相同結構補齊
];
完整資料涵蓋全國各省、直轄市、自治區與其下屬城市、區縣,篇幅可觀,這裡僅列出結構範例,實作時把完整 JSON 補上即可。
元件用索引(aid、bid)而非名稱來定位資料,這讓查找只需一次線性掃描,邏輯單純。逐層顯示模式靠 visibility 切換,優點是不改變版面高度;若改用 display,版面會跟著收縮,可依設計需求選擇。
若要進一步改良,可以考慮:把行政區資料改成外部 JSON 以檔案載入,避免 HTML 檔案過大;用事件 delegation 取代逐一綁定;以及為 select 加上 aria-label 等無障礙屬性,讓螢幕閱讀器能正確朗讀每個欄位的用途。