2011-11-25 85 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