DIV CSS 佈局教程網

jQuery 操作 select 下拉選單的完整語法整理
編輯:JavaScript綜合知識     

下拉選單的讀取、設定、增刪,在表單開發中出現頻率極高。以下把 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"]);

三、新增與刪除 option

// 在尾端追加
$("#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;

五、依 value 設定選中項

$("#nowamagic").val("Normal");
$("#nowamagic").get(0).value = value;

六、依 text 設定選中項

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", "上班");

七、清空 select

$("#nowamagic").empty();

若要保留預設的第一項(例如「請選擇」),可以只刪掉其餘選項:

$("#nowamagic").find("option:not(:first)").remove();

八、綁定事件

$("#select_id").on('change', function () {
  var val = $(this).val();
  loadRelated(val);          // 例如觸發二級聯動
});

jQuery 1.7 之後請用 on(),bind() 已被視為舊寫法。

九、常見地雷

  • attr 與 prop:設定 selected/checked 這類狀態請用 prop() 或 val(),不要用 attr("selected")。
  • option[text='4'] 選擇器:依文字比對時,若文字含單引號或特殊字元會失效,改用上面的遍歷寫法。
  • 動態新增後要重新綁定:用 on() 做事件委派可避免這個問題。
  • 依索引刪除會位移:連續刪除時索引會變動,建議從後往前處理或每次都重新查詢。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved