我试图在select控件中找到当前选定选项的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>
上面的代码给出了未定义,因为它的选择元素除了选项的父母之外。有任何想法吗?
解决方法
你在
ID selector中缺少#。
$('#sector_select').change(function () { // ↓ var label=$('#sector_select :selected').parent().attr('label'); console.log(label); });
你也有一个虚假的< / a>标签
<option value='' selected='selected'>All Sectors</a>
之后,风格可能会有所改善:
$('#sector_select').on('change',function () { var label = $(this.options[this.selectedIndex]).closest('optgroup').prop('label'); console.log(label); });
这仍然会记录为< 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
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); });