萬盛學電腦網

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

JavaScript 動態操作 Select 下拉選單:建立、新增、刪除、修改、取值完整 API 指南

原生 DOM API 完整對照表

操作原生代碼說明
建立 <select>var sel = document.createElement('select'); sel.id = 'mySel'; document.body.appendChild(sel);記得加入文檔樹
新增 Optionsel.add(new Option('顯示文字', 'value值'));或 sel.options.add(new Option(...)),IE 早期需 sel.add(opt, null)
插入到指定位置sel.add(new Option('文字','值'), sel.options[1]);第二個參數為參考節點
刪除所有sel.options.length = 0; 或 sel.innerHTML = '';最快清空
刪除指定索引sel.remove(index); 或 sel.options.remove(index);index 為 0-based
刪除選中項sel.remove(sel.selectedIndex);
取得選中值var val = sel.value; 或 sel.options[sel.selectedIndex].value單選直接 .value
取得選中文字var txt = sel.options[sel.selectedIndex].text;
取得所有選中值 (多選)[...sel.selectedOptions].map(o => o.value)ES6 寫法
修改指定項sel.options[index] = new Option('新文字','新值');直接替換
設定選中 (依值)sel.value = 'targetValue';最簡潔
設定選中 (依索引)sel.selectedIndex = index;
移除 <select>sel.parentNode.removeChild(sel); 或 sel.remove() (現代)

jQuery 簡化寫法

// 新增
$('#mySel').append($('

二級聯動範例 (省市選擇)

var cityData = {
    '北京': ['東城區','西城區','朝陽區'],
    '上海': ['黃浦區','徐匯區','長寧區'],
    '廣東': ['廣州','深圳','珠海']
};

$('#province').change(function() {
    var cities = cityData[this.value] || [];
    var $city = $('#city').empty();
    $city.append($('

效能優化:大量選項 (千條以上)

  • 使用 DocumentFragment 批次掛載,避免重繪:
var frag = document.createDocumentFragment();
data.forEach(function(item) {
    frag.appendChild(new Option(item.name, item.id));
});
select.appendChild(frag);
  • 或採用虛擬滾動/搜尋型下拉 (如 Select2, Choices.js, Tom Select)。
  • 避免在迴圈中操作 select.options 或 $().append()。
  • 常見坑點

    • selectedIndex = -1 可清除選擇 (單選)。
    • option.selected = true 多選時可多個為 true,單選會自動取消其他。
    • IE 下 select.add(option) 第二參數必須提供 (索引或 null),否則報錯。
    • 動態新增 optgroup:var g = document.createElement('optgroup'); g.label = '群組'; g.appendChild(opt); sel.appendChild(g);

    總結

    原生 HTMLSelectElement API (options, add, remove, selectedIndex, value) 功能完整、效能最佳。jQuery 封裝提供鏈式語法與跨瀏覽器一致性。大量資料請用 DocumentFragment 或虛擬化下拉元件。

    copyright © 萬盛學電腦網 all rights reserved