jquery - 选中复选框时更改标签

标签 jquery html css checkbox label

我有很多带有复选框的列表:

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

最佳答案

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/

请注意,我使用了事件委托(delegate),而不是将相同的处理程序绑定(bind)到每个复选框。

关于jquery - 选中复选框时更改标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10833982/

相关文章:

jquery - 为什么我无法获得图像的自然宽度?

asp.net - 用于 ASP.NET 的 jQuery 图表控件

php - PHP 中的 HTML <select> 使用 mysql 数据

html - CSS 选择器的嵌套

javascript - 谷歌地图全高风格angularjs

jquery - 如何将加载微调器添加到 WooCommerce 结帐页面

JQuery 添加/删除类 onClick

使用for循环的Javascript图像幻灯片

css - 如何定位 Ant Design 中的所有元素?

javascript - 关闭窗口弹出div