【问题标题】:Change label when checkbox is checked选中复选框时更改标签
【发布时间】:2012-06-05 17:35:16
【问题描述】:

我有很多类似这样的复选框的列表:

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

【问题讨论】:

    标签: jquery html css checkbox label


    【解决方案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 );
    });
    

    现场演示: http://jsfiddle.net/MGVHX/1/

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

    【讨论】:

    • 是的,这是一个不错的解决方案。简单但有效。
    【解决方案2】:

    您当前尝试在 input 元素上调用 toggleClass,而不是在 label 上。您可以使用parent 获取label:

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

    【讨论】:

      【解决方案3】:
      $(".filteritem").on('change', function(){
           $(this).closest('label').toggleClass('highlight');
      });
      

      FIDDLE

      【讨论】:

        猜你喜欢
        • 2015-01-05
        • 2021-01-12
        • 2018-05-17
        • 2013-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-07
        相关资源
        最近更新 更多