萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 動態操控 Select 下拉選單完整指南

核心 DOM API

HTMLSelectElement 提供豐富介面:

  • options:HTMLOptionsCollection,支援索引存取、add()、remove()
  • selectedIndex:當前選中索引(-1 為無選擇)
  • value:當前選中選項的 value 屬性值
  • options[selectedIndex].text:當前顯示文字

關鍵陷阱:刪除時索引漂移

刪除選項會導致後續選項索引前移,**必須從大到小迴圈**或**先收集要刪除的索引**:

// ❌ 錯誤:正向刪除會漏掉項目
for (let i = 0; i < select.options.length; i++) {
    if (select.options[i].selected) select.remove(i);
}

// ✅ 正確:反向迴圈
for (let i = select.options.length - 1; i >= 0; i--) {
    if (select.options[i].selected) select.remove(i);
}

// ✅ 替代:收集後批次刪除
const toRemove = [...select.selectedOptions].map(opt => opt.index);
toRemove.sort((a,b) => b - a).forEach(i => select.remove(i));

完整操控工具函數集

const SelectUtils = {
    // 1. 判斷 value 是否存在
    hasValue(select, value) {
        return [...select.options].some(opt => opt.value === value);
    },

    // 2. 新增選項(避免重複)
    addOption(select, text, value) {
        if (this.hasValue(select, value)) return false;
        select.add(new Option(text, value));
        return true;
    },

    // 3. 依 value 移除
    removeByValue(select, value) {
        for (let i = select.options.length - 1; i >= 0; i--) {
            if (select.options[i].value === value) {
                select.remove(i);
                return true;
            }
        }
        return false;
    },

    // 4. 移除所有被選中
    removeSelected(select) {
        [...select.selectedOptions].forEach(opt => select.remove(opt.index));
    },

    // 5. 更新文字
    updateText(select, value, newText) {
        const opt = select.querySelector(`option[value="${value}"]`);
        if (opt) { opt.text = newText; return true; }
        return false;
    },

    // 6. 依文字設定選中(第一個匹配)
    selectByText(select, text) {
        const opt = [...select.options].find(o => o.text === text);
        if (opt) { opt.selected = true; return true; }
        return false;
    },

    // 7. 依 value 設定選中
    selectByValue(select, value) {
        select.value = value; // 自動匹配,無匹配則 selectedIndex=-1
        return select.value === value;
    },

    // 8. 獲取當前 value
    getValue(select) { return select.value; },

    // 9. 獲取當前 text
    getText(select) { return select.options[select.selectedIndex]?.text ?? ""; },

    // 10. 獲取當前 index
    getIndex(select) { return select.selectedIndex; },

    // 11. 清空所有
    clear(select) { select.options.length = 0; }
};

使用範例

const sel = document.getElementById("mySelect");

SelectUtils.addOption(sel, "選項一", "1");
SelectUtils.addOption(sel, "選項二", "2");
SelectUtils.selectByValue(sel, "1");
console.log(SelectUtils.getText(sel)); // "選項一"

SelectUtils.removeSelected(sel); // 刪除用戶手動勾選的項目

完整互動 Demo HTML

<select id="demoSelect" multiple size="5"></select><br>
<input type="text" id="txt" placeholder="文字">
<input type="text" id="val" placeholder="值"><br>
<button onclick="add()">新增</button>
<button onclick="removeSel()">刪除選中</button>
<button onclick="clearAll()">清空</button>

<script>
const sel = document.getElementById("demoSelect");
const txt = document.getElementById("txt");
const val = document.getElementById("val");

function add() {
    if (txt.value && val.value) SelectUtils.addOption(sel, txt.value, val.value);
}
function removeSel() { SelectUtils.removeSelected(sel); }
function clearAll() { SelectUtils.clear(sel); }
</script>
copyright © 萬盛學電腦網 all rights reserved