下拉選單的讀寫操作來來去去就那幾種,這裡按「取值、設值、增刪」三類整理成速查表。
$("#select_id").change(function () { /* code... */ }); // 綁定 change 事件
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"); // 最大索引值
$("#select_id").get(0).selectedIndex = 1; // 選中索引為 1 的項
$("#select_id").val(4); // 選中 value 為 4 的項
$("#select_id option[text='jQuery']").attr("selected", true); // 選中 text 為 jQuery 的項
三種寫法各有用途:已知位置用 selectedIndex,已知值用 val()(最常見),只能對文字比對時才用最後一種。
$("#select_id").append("<option value='Value'>Text</option>"); // 追加到末尾
$("#select_id").prepend("<option value='0'>請選擇</option>"); // 插入到第一位
$("#select_id option:last").remove(); // 刪除最後一個
$("#select_id option[index='0']").remove(); // 刪除第一個
$("#select_id option[value='3']").remove(); // 刪除 value='3' 的項
$("#select_id option[text='4']").remove(); // 刪除 text='4' 的項
實務上還有幾個常見組合值得記住:清空全部用 $("#select_id").empty();重置回第一項則是先 val(0) 再 trigger('change'),記得觸發事件,否則依賴它的連動邏輯不會更新。
希望這篇對大家的 jQuery 開發有幫助。