Change label when checkbox is checked

允我心安 提交于 2020-01-11 13:39:08

问题


I have a lot of listst with checkboxes like so:

<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>

Every checkbox has an unique ID

I want to toggle the background-color of the label when it is checkt.

This is what i got but it does not work:

jQuery:

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

CSS:

.highlight {
    //change something
}

回答1:


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 );
});

Live demo: http://jsfiddle.net/MGVHX/1/

Notice that I use event delegation, instead of binding the same handler to every check-box.




回答2:


You are currently trying to call toggleClass on the input element, not the label. You can use parent to get the label:

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



回答3:


$(".filteritem").on('change', function(){
     $(this).closest('label').toggleClass('highlight');
});

FIDDLE



来源:https://stackoverflow.com/questions/10833982/change-label-when-checkbox-is-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!