萬盛學電腦網

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

jQuery Select 下拉框操作完全指南:獲取、設置、增刪、事件

下拉選擇框(<select>)是表單中常見控件。本文系統整理 jQuery 操作 Select 的核心方法,涵蓋值獲取、選項增刪、狀態設置、事件綁定等實戰場景。

一、基礎獲取操作

1. 綁定 change 事件

$("#select_id").change(function() {
    // 選項變更時觸發
});

2. 獲取選中項的文本、值、索引

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");       // 最大索引

3. 直接獲取選中文本/值/索引(簡寫)

$("#ddlRegType").find("option:selected").text(); // 文本
$("#nowamagic").val();                           // 值
$("#nowamagic").get(0).selectedIndex;            // 索引

二、設置選中狀態

1. 通過索引設置

$("#select_id").get(0).selectedIndex = 1; // 選中索引為 1 的項
$("#nowamagic").get(0).selectedIndex = index;

2. 通過值設置

$("#select_id").val(4);                          // 推薦
$("#nowamagic").attr("value", "Normal");
$("#nowamagic").val("Normal");
$("#nowamagic").get(0).value = value;

3. 通過文本設置

// 方式一:屬性選擇器(需完全匹配)
$("#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;
    }
}

三、選項增刪操作

1. 添加選項

$("#select_id").append(""); // 追加到末尾
$("#select_id").prepend("");   // 插入到首位

2. 刪除選項

$("#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='...'] 區分大小寫且需完全匹配
  • 操作 DOM 級屬性(如 selectedIndex)需用 .get(0) 或 [0] 取原生元素
  • jQuery 3.0+ 建議用 .prop() 處理布爾屬性(selected、disabled)

結語

掌握以上核心 API,可輕松應對 Select 控件 90% 以上的業務場景。實際開發中建議封裝為通用工具函數,統一風格、減少重複代碼。

copyright © 萬盛學電腦網 all rights reserved