0

私は次のようなチェックボックスを備えたリストをたくさん持っています:

<ul>
   <li><label class="highlight"><input type="checkbox" id="1" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="223" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="32" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="42" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="54" class="filteritem">Lorem Ipsum</label</li>
</ul>

<ul>
   <li><label class="highlight"><input type="checkbox" id="43" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="343" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="342" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="53" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="55" class="filteritem">Lorem Ipsum</label</li>
</ul>

すべてのチェックボックスには一意のIDがあります

チェックしたときにラベルの背景色を切り替えたい。

これは私が得たものですが、機能しません:

jQuery:

$(".filteritem").click(function(){
    $(this).toggleClass('highlight');
});

CSS:

.highlight {
    //change something
}
4

3 に答える 3

7

HTML:

<ul class="checkboxlist">
   <li><label><input type="checkbox" id="1"> Lorem Ipsum</label></li>
   <li><label><input type="checkbox" id="223"> Lorem Ipsum</label></li>
   <li><label><input type="checkbox" id="32"> Lorem Ipsum</label></li>
</ul>

JavaScript:

$( '.checkboxlist' ).on( 'click', 'input:checkbox', function () {
   $( this ).parent().toggleClass( 'highlight', this.checked );
});

ライブデモ: http: //jsfiddle.net/MGVHX/1/

すべてのチェックボックスに同じハンドラーをバインドする代わりに、イベント委任を使用していることに注意してください。

于 2012-05-31T12:55:17.837 に答える
2

現在、ではなく要素を呼び出そうとしてtoggleClassいます。を取得するために使用できます:inputlabelparentlabel

$(".filteritem").click(function(){
    $(this).parent().toggleClass('highlight');
});
于 2012-05-31T12:55:10.007 に答える
1
$(".filteritem").on('change', function(){
     $(this).closest('label').toggleClass('highlight');
});

フィドル

于 2012-05-31T12:55:05.733 に答える