通過 select.options 集合可獲取下拉框所有 <option> 元素,遍歷輸出文本、值或索引。
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<button onclick="getOptions()">輸出所有選項</button>
<script>
function getOptions() {
const select = document.getElementById('mySelect');
let txt = '所有選項: ';
for (let i = 0; i < select.length; i++) {
txt += '\n' + select.options[i].text; // 或 .value
}
alert(txt);
}
</script>
| 屬性/方法 | 說明 |
|---|---|
| options.length | 選項數量 |
| options[index] | 獲取指定索引 Option 對象 |
| options.add(option, before) | 插入選項 |
| options.remove(index) | 刪除選項 |
| selectedIndex | 當前選中索引 (-1 為無選擇) |
| value | 當前選中值(取首個選中) |
const opt = select.options[i];
opt.text; // 顯示文本
opt.value; // 提交值 (無 value 時等同 text)
opt.selected; // 是否選中 (可寫)
opt.disabled; // 是否禁用
opt.index; // 在 options 中的索引
// 獲取所有選中值(多選)
const selected = [...select.selectedOptions].map(o => o.value);
// 動態添加選項
select.append(new Option('新選項', 'new-value'));
// 批量設置
const fruits = ['蘋果','香蕉','橙子'];
fruits.forEach((text, i) => select.add(new Option(text, i)));
// 清空並重置
select.innerHTML = '';
select.options 是操作下拉選單的核心 API。掌握遍歷、增刪改、獲取選中值,結合 ES6 展開運算符與 selectedOptions,能高效處理表單選擇交互。