在動態表單、級聯下拉選單等場景,需要清空 <select> 現有選項並重新填充。本文比較三種常見清空方法的語法、效能與適用場景。
const select = document.getElementById('selectId');
select.options.length = 0; // 瞬間清空,原生優化
document.formName.selectName.options.length = 0;
name 屬性、表單結構固定、不利維護、效能同方法一但可讀性差。select.innerHTML = '';
<option> 上的事件監聽器/資料屬性、可能導致 XSS (若字串來自不可信來源)。// 測試代碼 (在 Console 執行)
const select = document.createElement('select');
for (let i = 0; i < 10000; i++) {
const opt = document.createElement('option');
opt.value = i; opt.text = `Item ${i}`;
select.appendChild(opt);
}
document.body.appendChild(select);
console.time('length=0');
select.options.length = 0;
console.timeEnd('length=0'); // ~0.5-1 ms
// 重新填充
for (let i = 0; i < 10000; i++) { /* ... */ }
console.time('innerHTML');
select.innerHTML = '';
console.timeEnd('innerHTML'); // ~15-30 ms (慢 20-50 倍)
<select id="city"><option value="">請選擇縣市</option></select>
<select id="district" disabled><option value="">請先選縣市</option></select>
<script>
const citySelect = document.getElementById('city');
const districtSelect = document.getElementById('district');
const data = {
'台北市': ['中正區','大同區','中山區'],
'新北市': ['板橋區','三重區','新莊區']
};
Object.keys(data).forEach(city => {
citySelect.add(new Option(city, city));
});
citySelect.addEventListener('change', () => {
const city = citySelect.value;
// 清空並重填
districtSelect.options.length = 0; // ★ 核心行
if (city) {
data[city].forEach(district => districtSelect.add(new Option(district, district)));
districtSelect.disabled = false;
} else {
districtSelect.add(new Option('請先選縣市', ''));
districtSelect.disabled = true;
}
});
</script>
select.options.length = 0** 清空選項。select.add(new Option(text, value)) 或 select.appendChild(option)。innerHTML、removeChild 迴圈、jQuery.empty() (內部仍用 innerHTML)。<option>。掌握正確清空方法,能顯著提升動態表單回應速度與使用者體驗。