下拉選擇框(<select>)是表單中常見控件。本文系統整理 jQuery 操作 Select 的核心方法,涵蓋值獲取、選項增刪、狀態設置、事件綁定等實戰場景。
$("#select_id").change(function() {
// 選項變更時觸發
});
var checkText = $("#select_id").find("option:selected").text(); // 文本
var checkValue = $("#select_id").val(); // 值
var checkIndex = $("#select_id").get(0).selectedIndex; // 索引
var maxIndex = $("#select_id option:last").attr("index"); // 最大索引
$("#ddlRegType").find("option:selected").text(); // 文本
$("#nowamagic").val(); // 值
$("#nowamagic").get(0).selectedIndex; // 索引
$("#select_id").get(0).selectedIndex = 1; // 選中索引為 1 的項
$("#nowamagic").get(0).selectedIndex = index;
$("#select_id").val(4); // 推薦
$("#nowamagic").attr("value", "Normal");
$("#nowamagic").val("Normal");
$("#nowamagic").get(0).value = value;
// 方式一:屬性選擇器(需完全匹配)
$("#select_id option[text='jQuery']").attr("selected", true);
// 方式二:遍歷匹配(推薦,支持模糊/邏輯判斷)
var count = $("#nowamagic option").length;
for (var i = 0; i < count; i++) {
if ($("#nowamagic").get(0).options[i].text === text) {
$("#nowamagic").get(0).options[i].selected = true;
break;
}
}
$("#select_id").append(""); // 追加到末尾
$("#select_id").prepend(""); // 插入到首位
$("#select_id option:last").remove(); // 刪除最後一項
$("#select_id option[index='0']").remove(); // 刪除索引 0
$("#select_id option[value='3']").remove(); // 刪除 value=3
$("#select_id option[text='4']").remove(); // 刪除 text=4
$("#nowamagic").empty(); // 移除所有子選項
| 需求 | 推薦寫法 | 備註 |
|---|---|---|
| 獲取選中文本 | $("#sel").find("option:selected").text() |
或 $("#sel option:selected").text() |
| 獲取選中值 | $("#sel").val() |
最簡潔,返回字符串 |
| 獲取選中索引 | $("#sel").prop("selectedIndex") |
推薦用 .prop() 替代 .get(0).selectedIndex |
| 設置選中值 | $("#sel").val("targetVal") |
自動匹配 option[value] |
| 動態添加選項 | $("#sel").append(new Option(text, val)) |
使用 DOM Option 對象更規範 |
| 清空並重置 | $("#sel").empty().append("") |
鏈式調用 |
val() 設置值時若無匹配選項,不會報錯也無效果[text='...'] 區分大小寫且需完全匹配selectedIndex)需用 .get(0) 或 [0] 取原生元素.prop() 處理布爾屬性(selected、disabled)掌握以上核心 API,可輕松應對 Select 控件 90% 以上的業務場景。實際開發中建議封裝為通用工具函數,統一風格、減少重複代碼。