Select Option 動態管理:原生 JS 完整 CRUD 操作指南
下拉框 (`
核心操作 API 速查
| 操作 | 原生 DOM API | 說明 |
| 添加選項 | `select.options.add(new Option(text, value), index)` | index 可選,插入位置 |
| 修改選項 | `option.text = newText; option.value = newValue;` | 直接修改屬性 |
| 刪除選項 | `select.remove(index)` 或 `select.options[index].remove()` | 索引刪除 |
| 清空所有 | `select.innerHTML = ''` 或 `while(select.options.length) select.remove(0)` | 後者兼容性更好 |
| 獲取選中值 | `select.value` | 單選直接取值 |
| 獲取選中文本 | `select.options[select.selectedIndex].text` | |
| 設置選中 | `select.value = targetValue` | 自動匹配 value |
| 遍歷選項 | `Array.from(select.options).map(o => ({text:o.text, value:o.value}))` | 轉為數組對象 |
完整封裝類 (ES6)
class SelectManager {
constructor(selectElement) {
this.select = typeof selectElement === 'string'
? document.querySelector(selectElement)
: selectElement;
if (!this.select || this.select.tagName !== 'SELECT') {
throw new Error('Invalid select element');
}
}
// 初始化選項
init(options = []) {
this.clear();
options.forEach(opt => this.add(opt.text, opt.value, opt.selected));
return this;
}
// 添加選項
add(text, value = text, selected = false, index = null) {
const option = new Option(text, value, false, selected);
if (index !== null && index >= 0 && index < this.select.options.length) {
this.select.add(option, this.select.options[index]);
} else {
this.select.add(option);
}
return this;
}
// 修改選項 (按索引或值)
update(identifier, newText, newValue) {
const index = typeof identifier === 'number'
? identifier
: this.findIndexByValue(identifier);
if (index >= 0) {
const opt = this.select.options[index];
if (newText !== undefined) opt.text = newText;
if (newValue !== undefined) opt.value = newValue;
}
return this;
}
// 刪除選項
remove(identifier) {
const index = typeof identifier === 'number'
? identifier
: this.findIndexByValue(identifier);
if (index >= 0) this.select.remove(index);
return this;
}
// 查找索引
findIndexByValue(value) {
return Array.from(this.select.options).findIndex(o => o.value === value);
}
// 同步輸入框 (雙向綁定)
bindInput(inputSelector, { onSelect = 'fill', onInput = 'select' } = {}) {
const input = document.querySelector(inputSelector);
if (!input) return this;
// 選中下拉項 → 填充輸入框
if (onSelect === 'fill') {
this.select.addEventListener('change', () => {
input.value = this.select.options[this.select.selectedIndex]?.text || '';
});
}
// 輸入框內容 → 查找/創建下拉項
if (onInput === 'select') {
input.addEventListener('input', () => {
const val = input.value;
const existing = this.findIndexByValue(val);
if (existing >= 0) {
this.select.selectedIndex = existing;
} else {
// 可選:自動添加
// this.add(val, val, true);
}
});
}
return this;
}
// 序列化 (保存/提交)
serialize(separator = ';') {
return Array.from(this.select.options)
.map(o => `${o.text}:${o.value}`)
.join(separator);
}
// 反序列化
deserialize(data, separator = ';') {
this.clear();
data.split(separator).forEach(pair => {
const [text, value] = pair.split(':');
if (text) this.add(text, value || text);
});
return this;
}
clear() {
this.select.innerHTML = '';
return this;
}
// 獲取所有選項數組
toArray() {
return Array.from(this.select.options).map(o => ({
text: o.text,
value: o.value,
selected: o.selected,
index: o.index
}));
}
}
// 使用示例
const manager = new SelectManager('#MySelect')
.init([
{ text: '我', value: 'me' },
{ text: '你', value: 'you' },
{ text: '他', value: 'he' }
])
.bindInput('#word-input'); // 雙向綁定輸入框
// 按鈕綁定
document.getElementById('btn-add').onclick = () =>
manager.add(document.getElementById('word-input').value);
document.getElementById('btn-del').onclick = () =>
manager.remove(manager.select.selectedIndex);
document.getElementById('btn-save').onclick = () =>
alert(manager.serialize());
HTML 結構
<select id="MySelect" size="10"></select><br>
<input type="text" id="word-input" /><br>
<button id="btn-add" type="button">增加</button>
<button id="btn-mod" type="button">修改</button>
<button id="btn-del" type="button">刪除</button>
<button id="btn-save" type="button">保存</button>
無障礙與 UX 增強
size 屬性顯示多行,避免下拉框遮擋內容
- 添加 `
- 大數據量時使用虛擬滾動或搜索過濾 (Select2/Choices.js/Tom Select)
- 鍵盤導航:`Home/End` 首尾、`Enter/Space` 選中、`Esc` 關閉
- 無障礙:`
現代庫推薦 (生產環境)
| 庫 | 體積 | 特性 | 適用場景 |
| Tom Select | ~20KB | 無依賴、虛擬滾動、標籤化、遠程搜索 | 複雜選擇器、標籤輸入 |
| Choices.js | ~15KB | 模塊化、可訪問性好、模板自定義 | 通用增強下拉 |
| Select2 | ~40KB | jQuery 依賴、生態豐富、遠程數據 | 舊項目、jQuery 技術棧 |