Jquery获取选择选项的OPTGROUP标签

Sir*_*jik 23 html jquery html-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>
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了undefined,因为它的select元素的读取父元素除了option.有任何想法吗?

Mat*_*all 54

你错过#ID选择器.

$('#sector_select').change(function ()
{
    //           ?
    var label=$('#sector_select :selected').parent().attr('label');
    console.log(label);
});
Run Code Online (Sandbox Code Playgroud)

你也有一个虚假的</a>标签

<option value='' selected='selected'>All Sectors</a>
Run Code Online (Sandbox Code Playgroud)

之后风格可以使用一些改进:

$('#sector_select').on('change', function ()
{
    var label = $(this.options[this.selectedIndex]).closest('optgroup').prop('label');
    console.log(label);
});
Run Code Online (Sandbox Code Playgroud)

这将仍然记录undefined<option>其不处于<optgroup>; 你如何处理这种情况取决于你.演示:http://jsfiddle.net/mattball/fyLJm/


只是想知道你是否可以编写一个函数来获取任何select元素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);
});?
Run Code Online (Sandbox Code Playgroud)