jQuery 获取选择选项的 OPTGROUP 的标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10093048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery get label of OPTGROUP of select option
提问by Sir Lojik
I am trying to find the value of the optgroup label of currently selected option in a select control. below is some html to show what im trying to do.
我试图在选择控件中找到当前选定选项的 optgroup 标签的值。下面是一些 html 来显示我正在尝试做什么。
<select id='sector_select' name='sector_select' data-placeholder="Select Sector..." style="width:200px;" class="chzn-select">
<option value='' selected='selected'>All Sectors</a>
<optgroup label="Consultancy Services">
<option value='Employment placement/ recruitment'>Employment placement/ recruitment</option>
</optgroup>
<optgroup label="Supplies">
<option value='Food, beverages and related products'>Food, beverages and related products</option>
</optgroup>
</select>
<script type="text/javascript">
$('#sector_select').change(function ()
{
var label=$('sector_select :selected').parent().attr('label');
console.log(label);
});
</script>
the above code gives undefined because its reading parent of select element other than option. any ideas?
上面的代码给出了 undefined 因为它的读取父元素不是选项。有任何想法吗?
回答by Matt Ball
You're missing the #
in the ID selector.
你缺少#
的ID选择。
$('#sector_select').change(function ()
{
// ↓
var label=$('#sector_select :selected').parent().attr('label');
console.log(label);
});
You've also got a spurious </a>
tag in
你也有一个虚假的</a>
标签
<option value='' selected='selected'>All Sectors</a>
The style could use some improvement, after that:
风格可以使用一些改进,之后:
$('#sector_select').on('change', function ()
{
var label = $(this.options[this.selectedIndex]).closest('optgroup').prop('label');
console.log(label);
});
This will still log undefined
for the <option>
which is not in an <optgroup>
; how you handle that scenario is up to you. Demo: http://jsfiddle.net/mattball/fyLJm/
这将仍然记录undefined
在<option>
其不处于<optgroup>
; 你如何处理这种情况取决于你。演示:http: //jsfiddle.net/mattball/fyLJm/
just wondering if you can write up a function that takes whatever select element id and returns optgroup label of selected item. the 'this' confuses me within the $(). a function i can use outside the onchange event
只是想知道您是否可以编写一个函数,该函数接受任何选择元素 id 并返回所选项目的 optgroup 标签。'this' 在 $() 中让我感到困惑。我可以在 onchange 事件之外使用的函数
function logOptgroupLabel(id)
{
var elt = $('#'+id)[0];
var label = $(elt.options[elt.selectedIndex]).closest('optgroup').prop('label');
console.log(label);
}
$('#sector_select').on('change', function () {
logOptgroupLabel(this.id);
});?