选中复选框时更改标签 [英] Change label when checkbox is checked

查看:176
本文介绍了选中复选框时更改标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多列表与复选框,如此:

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>

每个复选框都有一个唯一的ID

Every checkbox has an unique ID

这是我得到的,但不起作用:

This is what i got but it does not work:

jQuery:

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

CSS:

.highlight {
    //change something
}


推荐答案

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:

JavaScript:

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

在线演示 http://jsfiddle.net/MGVHX/1/

请注意,我使用 strong>,而不是将相同的处理程序绑定到每个复选框。

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

这篇关于选中复选框时更改标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆