萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 與 jQuery 獲取 Select 下拉框選中值的完整指南

在表單處理中,獲取 <select> 元素的選中值是高頻需求。原生 JavaScript 與 jQuery 提供了多種方式,各有優劣。本文系統梳理兩大陣營的核心 API,並對比實戰適用場景,助你靈活選型。

一、原生 JavaScript 方案

核心屬性與方法

  • selectedIndex:返回當前選中項的索引(從 0 開始),無選中時為 -1
  • options 集合:包含所有 <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

二、jQuery 方案詳解

方式一:選擇器直達

// 獲取選中項的文本
$('#testSelect option:selected').text();

// 獲取選中項的值
$('#testSelect option:selected').val();
// 或更簡潔
$('#testSelect').val();

// 獲取選中索引
$('#testSelect').prop('selectedIndex'); // 推薦用 prop
// 兼容舊版
$('#testSelect').get(0).selectedIndex;

方式二:find() 鏈式查找

$('#testSelect').find('option:selected').text();  // 文本
$('#testSelect').find('option:selected').val();   // 值

實戰增強:動態綁定 change 事件

$('#testSelect').on('change', function() {
    const $this = $(this);
    console.log('值:', $this.val());
    console.log('文本:', $this.find('option:selected').text());
    console.log('索引:', $this.prop('selectedIndex'));
});

三、進階場景與技巧

1. 多選框 (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);

2. 設置選中項

// 按 value 設置
$('#testSelect').val('targetValue');

// 按索引設置
$('#testSelect').prop('selectedIndex', 2);

// 按文本設置(需遍歷)
$('#testSelect option').filter(function() {
    return $(this).text() === '目標文本';
}).prop('selected', true);

3. 動態增減選項

// 追加
$('#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
  • 舊版 jQuery:.attr('selected') 僅反映初始 HTML,動態修改需用 .prop('selected', true)

六、總結

獲取 Select 值,核心就兩條路:原生 select.value 最輕量,jQuery $('#sel').val() 最統一。理解 selectedIndex、options 集合、:selected 偽類的底層關係,就能在任何框架甚至無框架環境下信手拈來。下次遇到下拉框交互,先問:「項目有 jQuery 嗎?需不需要文本?」兩秒定方案。

copyright © 萬盛學電腦網 all rights reserved