jquery操做Select方法

jQuery獲取Select選擇的Text和Value:

$("#select_id").change(function(){//code...}); //爲Select添加事件,當選擇其中一項時觸發
 
var checkText=$("#select_id").find("option:selected").text(); //獲取Select選擇的text
 
var checkValue=$("#select_id").val(); //獲取Select選擇的Value
 
var checkIndex=$("#select_id ").get(0).selectedIndex; //獲取Select選擇的索引值
 
var maxIndex=$("#select_id option:last").attr("index"); //獲取Select最大的索引值

jQuery添加/刪除Select的Option項:

$("#select_id").append("<option value='Value'>Text</option>"); //爲Select追加一個Option(下拉項)
 
$("#select_id").prepend("<option value='0'>請選擇</option>"); //爲Select插入一個Option(第一個位置)
 
$("#select_id option:last").remove(); //刪除Select中索引值最大Option(最後一個)
 
$("#select_id option[index='0']").remove(); //刪除Select中索引值爲0的Option(第一個)
 
$("#select_id option[value='3']").remove(); //刪除Select中Value='3'的Optiona
 
$("#select_id option[text='4']").remove(); //刪除Select中Text='4'的Optiona

內容清空:

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

設置value爲pxx的項選中

<select class="selector"></select>

$(".selector").val("pxx");

設置text爲pxx的項選中

<select class="selector"></select>

$(".selector").find("option[text='pxx']").attr("selected",true);
這裏有一箇中括號的用法,中括號裏的等號的前面是屬性名稱,不用加引號。不少時候,中括號的運用能夠使得邏輯變得很簡單。

獲取當前選中項的value

$(".selector").val();

獲取當前選中項的text

$(".selector").find("option:selected").text();
這裏用到了冒號,掌握它的用法並觸類旁通也會讓代碼變得簡潔。

不少時候用到select的級聯,即第二個select的值隨着第一個select選中的值變化。這在jquery中是很是簡單的。

$(".selector1").change(function(){
     // 先清空第二個
      $(".selector2").empty();
     // 實際的應用中,這裏的option通常都是用循環生成多個了
      var option = $("<option>").val(1).text("pxx");
      $(".selector2").append(option);
});
相關文章
相關標籤/搜索