27

選択コントロールで現在選択されているオプションの 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>

上記のコードは、オプション以外の選択要素の読み取り親であるため、未定義になります。何か案は?

4

1 に答える 1

59

ID セレクター#に がありません。

$('#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);
});

これは、 ;にないのログundefinedを記録します。そのシナリオをどのように扱うかはあなた次第です。デモ: http://jsfiddle.net/mattball/fyLJm/<option><optgroup>


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);
});​
于 2012-04-10T16:57:14.483 に答える