| 操作 | 原生代碼 | 說明 |
|---|---|---|
| 建立 <select> | var sel = document.createElement('select'); sel.id = 'mySel'; document.body.appendChild(sel); | 記得加入文檔樹 |
| 新增 Option | sel.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() (現代) |
// 新增
$('#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);
select.options 或 $().append()。selectedIndex = -1 可清除選擇 (單選)。option.selected = true 多選時可多個為 true,單選會自動取消其他。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 或虛擬化下拉元件。