下拉選單的讀取、設定、增刪,在表單開發中出現頻率極高。以下把 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"); // 最後一項的索引
// 依索引設定
$("#select_id").get(0).selectedIndex = 1;
// 依 value 設定(最推薦,語意清楚)
$("#select_id").val("4");
// 依文字設定
$("#select_id option[text='jQuery']").attr("selected", true);
用 val() 設定是最穩定的方式。若 select 設定了 multiple,val() 可以傳陣列一次選多項:
$("#multi").val(["a", "c"]);
// 在尾端追加
$("#select_id").append("<option value='Value'>Text</option>");
// 在首端插入
$("#select_id").prepend("<option value='0'>請選擇</option>");
// 刪除最後一項
$("#select_id option:last").remove();
// 刪除索引為 0 的項
$("#select_id option[index='0']").remove();
// 依 value 刪除
$("#select_id option[value='3']").remove();
// 依 text 刪除
$("#select_id option[text='4']").remove();
實務上更建議用 <option> 物件 API 建立,效能比解析 HTML 字串好:
$("#select_id").append(new Option("文字", "value"));
// index 為索引值
$("#nowamagic").get(0).selectedIndex = index;
$("#nowamagic").val("Normal");
$("#nowamagic").get(0).value = value;
select 沒有內建的「依文字選取」API,需要自己遍歷比對:
function selectByText(id, text) {
var sel = document.getElementById(id);
for (var i = 0; i < sel.options.length; i++) {
if (sel.options[i].text === text) {
sel.options[i].selected = true;
break;
}
}
}
selectByText("nowamagic", "上班");
$("#nowamagic").empty();
若要保留預設的第一項(例如「請選擇」),可以只刪掉其餘選項:
$("#nowamagic").find("option:not(:first)").remove();
$("#select_id").on('change', function () { var val = $(this).val(); loadRelated(val); // 例如觸發二級聯動 });jQuery 1.7 之後請用
on(),bind()已被視為舊寫法。九、常見地雷
prop() 或 val(),不要用 attr("selected")。on() 做事件委派可避免這個問題。