核心方法
<select id="Mmonth">
<option>1</option>
</select>
<input type="button" onclick="a()" value="添加"/>
<script>
function a() {
document.getElementById("Mmonth").options.add(new Option("1", "1"));
}
</script>
Option 構造函數詳解
new Option(text, value, defaultSelected, selected)
// text: 顯示文本
// value: 提交值(可省略,默認等於 text)
// defaultSelected: 默認選中狀態(布爾)
// selected: 當前選中狀態(布爾)
三種添加方式對比
| 方式 | 代碼 | 優缺點 |
| options.add() | select.options.add(new Option(txt, val)) | 標準 DOM API,支持插入位置(第二參數),IE 早期需併發 |
| appendChild | select.appendChild(new Option(txt, val)) | 通用節點插入,只能追加到末尾 |
| innerHTML | select.innerHTML += '<option>...</option>' | 簡潔但銷毀重建所有選項,丟失事件綁定、選中狀態 |
現代最佳實踐
function addOption(selectId, text, value, {selected = false} = {}) {
const select = document.getElementById(selectId);
const opt = new Option(text, value, false, selected);
select.appendChild(opt); // 或 select.options.add(opt)
}
// 批量添加
function addOptions(selectId, options) {
const select = document.getElementById(selectId);
const fragment = document.createDocumentFragment();
options.forEach(({text, value, selected}) => {
fragment.appendChild(new Option(text, value, false, selected));
});
select.appendChild(fragment);
}
// 使用
addOption('Mmonth', '2月', '2');
addOptions('Mmonth', [
{text: '3月', value: '3'},
{text: '4月', value: '4', selected: true}
]);
常見操作
- 獲取選中值:
select.value 或 select.options[select.selectedIndex].value
- 獲取選中文本:
select.options[select.selectedIndex].text
- 刪除選項:
select.remove(index) 或 select.options[index] = null
- 清空:
select.innerHTML = '' 或循環 remove(0)。
- 修改選項:
option.text = '新文本'、option.value = '新值'。