下拉選單的選項不一定要寫在 HTML 裡。用 createElement 動態建立 option 並附加到 select 上,是處理「選項來自資料」的標準做法。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>利用 DOM 生成下拉列表框</title>
</head>
<body onload="setFun()">
<form>
<select name="area" id="area">
<option value="0">沒有地區</option>
</select>
</form>
<script language="javascript">
function setFun() {
var id = new Array(1, 2, 3);
var value = new Array("貴州", "重慶", "四川");
var select = document.getElementById("area");
select.length = 1; // 只保留一個選項
select.options[0].selected = true; // 預設選中第一個
for (var x = 0; x < id.length; x++) {
var option = document.createElement("option");
option.setAttribute("value", id[x]); // 設定 value 屬性
option.appendChild(document.createTextNode(value[x])); // 設定顯示文字
select.appendChild(option); // 加到 select
}
}
</script>
</body>
</html>
select.length = 1 是直接截斷選項集合,只留第一項。這是 HTMLSelectElement 少見的可寫屬性,很方便但也容易誤用——若原本沒有那麼多選項,設更大的值會產生空白項目。
用 createTextNode 而非 innerHTML 設定文字,可以避免資料被當成 HTML 解析。這個習慣在處理使用者輸入時是必要的安全措施。
用 id 陣列與 value 陣列兩個平行陣列對應,是早期常見做法,但很容易錯位。用物件陣列更安全:
const areas = [
{ id: 1, name: '貴州' },
{ id: 2, name: '重慶' },
{ id: 3, name: '四川' }
];
const select = document.getElementById('area');
areas.forEach(function (area) {
const option = document.createElement('option');
option.value = String(area.id);
option.textContent = area.name; // 比 createTextNode 簡潔
select.appendChild(option);
});
用 new Option:最精簡
areas.forEach(a => select.add(new Option(a.name, a.id)));
用 insertAdjacentHTML:一次寫入,效能最好
select.insertAdjacentHTML('beforeend',
areas.map(a => `<option value="${a.id}">${a.name}</option>`).join('')
);
但這種寫法在 name 含使用者輸入時必須先做 HTML 編碼,否則有 XSS 風險。純資料情境下用 createElement 比較安全。
清空後重建:資料更新時最乾淨的做法
function fillSelect(select, items) {
select.textContent = ''; // 清空,比 options.length = 0 明確
items.forEach(item => {
const opt = document.createElement('option');
opt.value = item.id;
opt.textContent = item.name;
select.appendChild(opt);
});
}
動態產生的選單若作為表單提交,後端仍必須驗證收到的值是否在允許清單中。前端選單可以被開發者工具任意竄改,不可作為唯一把關。