2011-11-25 31 views
1
<optgroup label="Food"> 

選擇OPTGROUP我該怎麼辦,所以當你按下這個鏈接上點擊jQuery中

<a class='clickMe' id='Food'>Show </a> 

應該在optgroup選擇第一個<option>,具有OPTGROUP標籤「食品」(取從鏈接中的 'id' 屬性)

$('.clickMe').live('click', function(){ 
var label = $(this).attr('id'); 

// How can i select the first option from the optgroup label here? 

}); 

也許,如果有幫助,選擇具有名稱= 「產品[] [類別]」

回答

1
//bind a click event handler to any elements that have the `.clickMe` class 
$('.clickMe').live('click', function(){ 

    //change the value of the select input to the first option in the optgroup that has a label that is equal to the id of the link clicked 
    $('select').val($('optgroup[label="' + this.id + '"]').children('option:first').val()); 
}); 

下面是該解決方案的的jsfiddle:http://jsfiddle.net/jasper/LqmJG/

這裏有神奇的上方快速擊穿:

  • $('optgroup[label="' + this.id + '"]'):選擇選項組標籤與被點擊鏈接的ID相匹配。
  • .children('option:first').val():選擇第一個選項(它是已選擇的optgroup標籤的子項)並獲取其值。
  • 上述兩行都用於獲取所選optgroup中第一個選項的值,然後使用該值設置<select>元素的值。
0

嘗試 -

var opt = $("select > optgroup[label=Food] > option:first"); 
+0

沒有工作了要麼 – Karem

+0

這裏有一個工作的例子 - http://jsfiddle.net/pR8qF/ – ipr101

+0

爲什麼犯規「德系車」的工作,如果我輸入的是,在拉貝=? – Karem