jQuery 對表單元素的操作非常直覺。以下整理下拉選單(Select)最常遇到的幾種情境。
// 動態增加一個 option
$("#selectId").append("<option value='" + optionval + "'>" + text + "</option>");
// 選中剛剛新增的那一項
$("#selectId").val(optionval);
第二行是關鍵。新增之後通常希望能立刻跳到該選項,而 .val() 不只是「取值」,指定參數時它也是「設值」。
// 取得選中選項的文字
$("#selectId option:selected").text();
// 取得選中選項的 value
$("#selectId").val();
// 清空所有選項
$("#selectId").empty();
// 大量加入選項
$.each(dataList, function(i, item){
$("#selectId").append("<option value='" + item.id + "'>" + item.name + "</option>");
});
// 依 value 移除某一項
$("#selectId option[value='3']").remove();
// 取得選中項的索引
var idx = $("#selectId")[0].selectedIndex;
// 依索引選中
$("#selectId")[0].selectedIndex = 2;
// 遍歷所有選項
$("#selectId option").each(function(){
console.log($(this).val(), $(this).text());
});
用迴圈逐次 append 在選項數量多時會明顯卡頓,因為每次 append 都可能觸發一次 DOM 更新。比較好的做法是先組出一整段 HTML 字串再一次插入:
var html = "";
$.each(dataList, function(i, item){
html += "<option value='" + item.id + "'>" + item.name + "</option>";
});
$("#selectId").html(html);
若資料量再大一點,改用 $("<option>") 建立文件片段後一次附加,會比字串拼接更有效率,也更不容易因為資料中含有引號而破壞 HTML 結構。