jquery操做select取值賦值與設置選中

好比:javascript

<select class="selector">

</select>

一、設置value爲pxx的項選中 html

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

二、設置text爲pxx的項選中 java

$(".selector").find("option[text='pxx']").attr("selected",true);

這是一箇中括號的用法,中括號裏的等號的前面是屬性名稱,不用加引號。
不少時候,中括號的運用能夠使得邏輯變得很簡單。jquery

三、獲取當前選中項的value app

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

四、獲取當前選中項的text spa

$(".selector").find("option:selected").text();

這裏用到了冒號,掌握它的用法並觸類旁通也會讓代碼變得簡潔。 code

 

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

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

 

選中第一個ip

$("#id option:first").prop("selected", 'selected');
相關文章
相關標籤/搜索