gpt4 book ai didi

jquery - 单击选择 jQuery 中的 optgroup

转载 作者:行者123 更新时间:2023-12-01 04:23:41 27 4
gpt4 key购买 nike

<optgroup label="Food">

当您按下此链接时我该怎么做

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

它应该选择第一个 <option>optgroup ,具有 optgroup 标签“Food”(取自链接中的“id”属性)

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

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

});

也许如果有帮助的话,选择有 name="product[][category]"

最佳答案

//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 标记的子选项)并获取其值。
  • 上面这两行都用于获取所选选项组中第一个选项的值,然后该值用于设置 <select> 的值元素。

关于jquery - 单击选择 jQuery 中的 optgroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8273806/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com