简体   繁体   English

jQuery toggleClass不适用于label

[英]jQuery toggleClass doesn't work with label

Why doesn't toggleClass() work with label element? 为什么toggleClass()不使用label元素? And how can I fix it? 我该如何解决?

If you only click on the label (not the checkbox) you'll see the color doesn't change. 如果您只点击标签(而不是复选框),您将看到颜色不会改变。

jsFiddle 的jsfiddle

 $(document).ready(function() { $('.filter-set label').click(function() { $(this).toggleClass('active'); }); }); 
 .active { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="filter-set"> <ul> <li><label><input name="checkbox" type="checkbox"> label 1</label></li> <li><label><input name="checkbox" type="checkbox"> label 2</label></li> <li><label><input name="checkbox" type="checkbox"> label 3</label></li> </ul> </div> 

You just need change event binding instead of click 您只需要change事件绑定而不是click

$('.filter-set label').change(function() {
    $(this).toggleClass("active");
  });

Working example : http://jsfiddle.net/DinoMyte/8gz0jsnq/5/ 工作示例: http//jsfiddle.net/DinoMyte/8gz0jsnq/5/

Explanation : 说明:

It turns out that when you click on the label, it also invokes the click event on the input:checkbox ( because of nested element wrapping ). 事实证明,当您click标签时,它还会调用input:checkbox上的click事件(因为嵌套元素换行)。 Because of this, the 1st event on the label does sets the class 'active' correctly , however with the subsequent click event on the checkbox toggles it back to empty ( basically removes the class ' active '). 因此,标签上的第一个事件确实正确地设置了'active'类,但是checkbox上的后续单击事件将其切换回为empty (基本上删除了类“ active ”)。

The effects of the above mentioned can be seen here : http://jsfiddle.net/DinoMyte/8gz0jsnq/6/ 上面提到的效果可以在这里看到: http//jsfiddle.net/DinoMyte/8gz0jsnq/6/

Binding a change event would only trigger the event once ( only for checkbox ) which would toggle the class correctly. 绑定change事件只会触发事件一次(仅用于checkbox ),这将正确切换类。

What you want to do here is use the checkbox change event instead: 您要在此处执行的操作是使用复选框更改事件:

$("input[type=checkbox]").on('change', function () {
  $(this).parent().toggleClass("active");
});

Works when clicking on the checkbox directly and on the label: 直接单击复选框并在标签上工作:

https://jsfiddle.net/s6fx1Lez/ https://jsfiddle.net/s6fx1Lez/

For more details on why this is happening: 有关为何发生这种情况的详细信息:

https://stackoverflow.com/a/8386513/660694 https://stackoverflow.com/a/8386513/660694

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM