萬盛學電腦網

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

JavaScript Select/Option 完整操作指南:從建立到事件處理的標準化實作

標準 DOM API 操作 Select

1. 動態建立 Select 元素


function createSelect(id, options, selectedValue) {
    var select = document.createElement('select');
    select.id = id;
    select.name = id;
    
    options.forEach(function(opt) {
        var option = document.createElement('option');
        option.value = opt.value;
        option.textContent = opt.text;
        if (opt.value === selectedValue) option.selected = true;
        select.appendChild(option);
    });
    
    return select;
}

// 使用
var citySelect = createSelect('city', [
    { value: 'tp', text: '台北市' },
    { value: 'tc', text: '台中市' },
    { value: 'kh', text: '高雄市' }
], 'tc');

document.getElementById('container').appendChild(citySelect);

2. 新增選項 (標準相容寫法)


function addOption(select, text, value, index) {
    var option = new Option(text, value);
    // index 為插入位置,undefined 為附加到末尾
    select.add(option, index !== undefined ? select.options[index] : null);
}

function addOptions(select, items, textKey, valueKey) {
    var fragment = document.createDocumentFragment();
    items.forEach(function(item) {
        var text = textKey ? item[textKey] : item;
        var value = valueKey ? item[valueKey] : item;
        fragment.appendChild(new Option(text, value));
    });
    select.appendChild(fragment); // 批次寫入,單次 Reflow
}

3. 刪除選項


// 刪除全部
function clearOptions(select, keepFirst = 0) {
    var len = select.options.length;
    for (var i = len - 1; i >= keepFirst; i--) {
        select.remove(i);
    }
}

// 刪除指定值
function removeOptionByValue(select, value) {
    for (var i = select.options.length - 1; i >= 0; i--) {
        if (select.options[i].value === value) select.remove(i);
    }
}

// 刪除選中項
function removeSelected(select) {
    var idx = select.selectedIndex;
    if (idx >= 0) select.remove(idx);
}

4. 取得/設定值與文字


function getSelectedValue(select) {
    return select.value; // 直接取值,無選中回傳空字串
}

function getSelectedText(select) {
    var idx = select.selectedIndex;
    return idx >= 0 ? select.options[idx].text : '';
}

function setSelectedValue(select, value) {
    select.value = value; // 不存在則 selectedIndex = -1
}

function setSelectedIndex(select, index) {
    if (index >= 0 && index < select.options.length) {
        select.selectedIndex = index;
    }
}

5. 修改選項內容


function updateOption(select, index, newText, newValue) {
    if (index >= 0 && index < select.options.length) {
        var opt = select.options[index];
        opt.text = newText;
        opt.value = newValue !== undefined ? newValue : newText;
    }
}

6. 完整互動範例:雙向編輯


<select id="editableSelect" multiple size="5"></select>
<input type="text" id="optText" placeholder="選項文字">
<input type="text" id="optValue" placeholder="選項值">
<button onclick="addOpt()">新增</button>
<button onclick="editOpt()">修改選中</button>
<button onclick="delOpt()">刪除選中</button>

<script>
var sel = document.getElementById('editableSelect');

function addOpt() {
    var t = document.getElementById('optText').value;
    var v = document.getElementById('optValue').value || t;
    if (!t) return alert('請輸入文字');
    sel.add(new Option(t, v));
    document.getElementById('optText').value = '';
    document.getElementById('optValue').value = '';
}

function editOpt() {
    var idx = sel.selectedIndex;
    if (idx < 0) return alert('請先選中項目');
    var t = document.getElementById('optText').value;
    var v = document.getElementById('optValue').value;
    if (!t) return alert('請輸入文字');
    sel.options[idx].text = t;
    sel.options[idx].value = v || t;
}

function delOpt() {
    var idx = sel.selectedIndex;
    if (idx < 0) return alert('請先選中項目');
    sel.remove(idx);
}
</script>

jQuery 版本對照 (維舊專案用)


var $sel = $('#mySelect');

// 新增
$sel.append(new Option('文字', '值'));
$sel.append('');

// 刪除全部
$sel.empty();
// 保留第一項
$sel.find('option:not(:first)').remove();

// 刪除選中
$sel.find('option:selected').remove();

// 取值/取文字
$sel.val();
$sel.find('option:selected').text();

// 修改選中
$sel.find('option:selected').text('新文字').val('新值');

// 綁定事件
$sel.on('change', function() {
    console.log(this.value, $(this).find('option:selected').text());
});

避坑指南

  1. 選項 value 重複:select.value 只會選中第一個匹配項,避免重複 value
  2. selectedIndex = -1:設定不存在的 value 會導致無選中狀態
  3. multiple 時:selectedIndex 只回傳第一個選中項,用 selectedOptions 取得全部
  4. Option() 建構子參數:new Option(text, value, defaultSelected, selected) 後兩參數鮮用
  5. 表單提交:只有 selected 的 option 會隨表單送出,disabled 的不送出

無障礙增強




// 鍵盤操作:上下鍵選擇、Enter 確認、Esc 關閉 (原生支援)
// 螢幕閱讀器會朗讀 optgroup label
copyright © 萬盛學電腦網 all rights reserved