0

私のjsコードで奇妙な動作があります。ここで JsFiddle を実行します: http://jsfiddle.net/wf8G6/2/

特定のチェックボックスをオンにしたときに、選択の「選択されたオプション」を更新したい...

実際には、イベントをトリガーするには3回クリックする必要があります...

チェックボックスをオンにする => 何も起こらない チェックボックスをオフにする => 何も起こらない チェックボックスをオンにする => 動作する ...

ここに私のHTMLがあります

<fieldset class="attribute_fieldset" rel="">
    <input class="left cb_group_5" type="checkbox" value="group_5" /> 

    <select name="group_5" id="group_5" class="attribute_select hidden">
        <option value="23" selected="selected" title="non">non</option>
        <option value="24" title="oui">oui</option>
    </select>
</fieldset>

ここに私のJSがあります

//if we check a checkbox, we trigger a click on the select below
$('.attribute_fieldset input[type=checkbox]').change(function () {
    var target = '#' + $(this).val();
    $(target + ' option').removeAttr('selected');
    if (this.checked) {
        $(target + ' option[title="oui"]').attr('selected', 'selected');
    } else {
        $(target + ' option[title="non"]').attr('selected', 'selected');
    }
    $(target).trigger('change');
});

私は何を間違っていますか?コミュニティを助けてください=)

4

1 に答える 1

1

正しく理解できたら、チェックボックスをクリックしたかどうかに応じてドロップダウンを変更してください。

あなたのコードには次の行があります

$(target + ' option').removeAttr('selected');

すべてのオプションから選択した属性を削除する理由がわかりません。削除すると、コードは正常に動作します

$('.attribute_fieldset input[type=checkbox]').change(function(){

    var target = '#'+$(this).val();


    if(this.checked)
    {
        $(target+' option[title="oui"]').attr('selected','selected');
    }
    else
    {
        $(target+' option[title="non"]').attr('selected','selected');
    }


});

http://jsfiddle.net/wf8G6/3/

また、余談ですが、そのままの方法で要素を参照し続けない方が良いです。より効率的な方法は次のとおりです

$('.attribute_fieldset input[type=checkbox]').change(function(){

    var target = $('#'+$(this).val());


    if(this.checked)
    {
        $('option[title="oui"]',target).attr('selected','selected');

    }
    else
    {
        $('option[title="non"]',target).attr('selected','selected');
    }


});
于 2013-10-18T14:32:13.907 に答える