DIV CSS 佈局教程網

jQuery 操作下拉選單 select 的常用語法整理
編輯:JQuery特效代碼     

下拉選單的讀取、設定、動態增刪,是表單開發的高頻操作。以下把常用語法整理成一份可直接複用的清單。

讀取目前選項

$("#select_id").change(function(){ /* 選擇其中一項時觸發 */ });

var checkText  = $("#select_id").find("option:selected").text(); // 選中項的文字
var checkValue = $("#select_id").val();                          // 選中項的 value
var checkIndex = $("#select_id").get(0).selectedIndex;           // 選中項的索引
var maxIndex   = $("#select_id option:last").attr("index");      // 最大索引值

設定選中項

$("#select_id").get(0).selectedIndex = 1;                    // 依索引設定
$("#select_id").val(4);                                        // 依 value 設定
$("#select_id option[text='jQuery']").attr("selected", true);  // 依文字設定

簡寫版本

// 取得選中項的文字
$("#ddlRegType").find("option:selected").text();

// 取得選中項的 value
$("#nowamagic").val();

// 取得選中項的索引
$("#nowamagic").get(0).selectedIndex;

動態增刪 option

$("#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();                    // 刪除索引為 0 的項
$("#select_id option[value='3']").remove();                    // 刪除 value=3 的項
$("#select_id option[text='4']").remove();                     // 刪除文字為 4 的項

依不同依據設定選中項

// 依索引
$("#nowamagic").get(0).selectedIndex = index;

// 依 value(三種寫法擇一)
$("#nowamagic").attr("value", "Normal");
$("#nowamagic").val("Normal");
$("#nowamagic").get(0).value = value;

依文字設定時沒有現成方法,需自行遍歷比對:

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;
  }
}

清空

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

實務建議

幾個可以讓程式碼更乾淨的做法:

  • 用 .val() 取代 .attr("value"),語意更清楚,也不必取 DOM 節點。
  • 設定選中項後,若要觸發綁定的事件,記得補上 .trigger("change"),因為程式設值不會自動觸發 change。
  • 建立 option 時若文字來自使用者輸入,應改用 $("<option>").val(v).text(t) 這種屬性式寫法,避免文字中的引號破壞 HTML。
  • 批次清空重建時,可先把整個 select 替換掉,比逐項 remove 效能更好。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved