jQuery:找到< optgroup>对于< select>中的选定值,元件 [英] jQuery: find the <optgroup> for a selected value in a <select> element
本文介绍了jQuery:找到< optgroup>对于< select>中的选定值,元件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含不同选项组的下拉菜单。如果有人选择了一个选项,我如何检查它属于哪个optgroup?例如,如果选择了ferrari,您将如何确定它属于哪个optgroup?
I have a dropdown menu with different option groups. If someone selects an option, how can I check which optgroup it belongs to? For example if 'ferrari' were selected, how would you determine which optgroup it belongs to?
随意使用jQuery或原始javascript。
Feel free to use jQuery or raw javascript.
<select name="testSelect">
<optgroup label="fruits">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="pears">Pears</option>
</optgroup>
<optgroup label="cars">
<option value="ford">ford</option>
<option value="toyota">toyota</option>
<option value="ferrari">ferrari</option>
</optgroup>
</select>
推荐答案
您可以使用jQuery执行此操作:
You can do this using jQuery:
$('select').change(function() {
var selected = $(':selected', this);
alert(selected.closest('optgroup').attr('label'));
});
在这里查看一个生动的例子: http://jsfiddle.net/ jkeyes / zjLCp / 1 /
See a live example here: http://jsfiddle.net/jkeyes/zjLCp/1/
更新:可以使用父母
http://jsfiddle.net/jkeyes/zjLCp/2/
selected.parent()
这篇关于jQuery:找到< optgroup>对于< select>中的选定值,元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文