在表單處理中,獲取 <select> 元素的選中值是高頻需求。原生 JavaScript 與 jQuery 提供了多種方式,各有優劣。本文系統梳理兩大陣營的核心 API,並對比實戰適用場景,助你靈活選型。
selectedIndex:返回當前選中項的索引(從 0 開始),無選中時為 -1options 集合:包含所有 <option> 元素option.value / option.text:獲取值與顯示文本const select = document.getElementById('testSelect');
const index = select.selectedIndex; // 索引
const value = select.options[index].value; // value 值
const text = select.options[index].text; // 顯示文本
IE 早期版本下 select.value 直接返回選中值,現代瀏覽器均支持,推薦優先使用:
// 現代瀏覽器通用寫法
const value = select.value; // 直接獲取 value
// 獲取選中項的文本
$('#testSelect option:selected').text();
// 獲取選中項的值
$('#testSelect option:selected').val();
// 或更簡潔
$('#testSelect').val();
// 獲取選中索引
$('#testSelect').prop('selectedIndex'); // 推薦用 prop
// 兼容舊版
$('#testSelect').get(0).selectedIndex;
$('#testSelect').find('option:selected').text(); // 文本
$('#testSelect').find('option:selected').val(); // 值
$('#testSelect').on('change', function() {
const $this = $(this);
console.log('值:', $this.val());
console.log('文本:', $this.find('option:selected').text());
console.log('索引:', $this.prop('selectedIndex'));
});
multiple) 處理<select id="multi" multiple>
<option value="a">A</option>
<option value="b" selected>B</option>
<option value="c" selected>C</option>
</select>
// jQuery 獲取多個值(返回數組)
$('#multi').val(); // ["b", "c"]
// 原生獲取
const selected = Array.from(multi.selectedOptions).map(o => o.value);
// 按 value 設置
$('#testSelect').val('targetValue');
// 按索引設置
$('#testSelect').prop('selectedIndex', 2);
// 按文本設置(需遍歷)
$('#testSelect option').filter(function() {
return $(this).text() === '目標文本';
}).prop('selected', true);
// 追加
$('#testSelect').append('');
// 前置
$('#testSelect').prepend('');
// 刪除最後一項
$('#testSelect option:last').remove();
// 刪除指定 value
$('#testSelect option[value="3"]').remove();
// 清空
$('#testSelect').empty();
| 場景 | 推薦方案 | 理由 |
|---|---|---|
| 簡單頁面、無 jQuery 依賴 | 原生 select.value | 零依賴、效能最高、代碼簡潔 |
| 已引入 jQuery、需鏈式操作 | $('#sel').val() | API 統一、鏈式調用、跨瀏覽器一致 |
| 需同時獲取文本與值 | find('option:selected') | 單次查找複用、避免重複選擇器解析 |
| 多選框批量操作 | 原生 selectedOptions + map | 原生數組方法靈活、無需額外庫 |
$('#tesetSelect') (typo) 導致選不到元素 → 善用 IDE 自動完成selectedIndex = -1,.val() 返回空字符串 → 判斷邏輯要兜底change 或手動 .val(newVal) 同步 UI.attr('selected') 僅反映初始 HTML,動態修改需用 .prop('selected', true)獲取 Select 值,核心就兩條路:原生 select.value 最輕量,jQuery $('#sel').val() 最統一。理解 selectedIndex、options 集合、:selected 偽類的底層關係,就能在任何框架甚至無框架環境下信手拈來。下次遇到下拉框交互,先問:「項目有 jQuery 嗎?需不需要文本?」兩秒定方案。