带标签元素的toggleClass的奇怪行为 [英] Strange behaviour of toggleClass with label element

查看:94
本文介绍了带标签元素的toggleClass的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天早些时候,我回答了这个问题.问题是关于使用jQuery在label元素上切换类.考虑以下HTML:

<label id="test">Test <input type="checkbox"></label>

以及以下jQuery:

$("#test").click(function() {
    $(this).toggleClass("testClass");
});

当我单击label时,我希望将testClass类应用于该元素(因为在页面加载时它没有该类).但是,什么也没有发生.在此处亲自查看.我没有在IE中尝试过,但是在Chrome或Firefox中无法正常工作.我相信它可以从以前链接到的问题在IE中正常工作.

逐步执行jQuery中的 toggleClass方法源,似乎发生的事情是立即添加和删除了该类.

如果将input元素移到label之外,则会按预期添加类:

<label id="test" for="cb">Test</label>
<input type="checkbox" id="cb">

您可以在此处看到一个正在运行的人.所以,我的问题是,为什么第一个示例在第一次单击时似乎没有添加类?我是否遗漏了明显地明显的东西?

解决方案

问题似乎源于这样的事实:当您嵌套了input时,click事件被触发两次(从而使切换无效).元素.我尚未在所有浏览器上都进行过测试,但这似乎是在FF8中发生的.

尝试在此示例中单击标签: http://jsfiddle.net/cRnJS/

显然,单击label元素会在其关联的input上触发一个click事件(这就是检查/取消选中工作的原因),并且该事件向上冒泡,因此在父级label中第二次触发它.

Earlier today I answered this question. The question is about toggling a class on a label element with jQuery. Consider the following HTML:

<label id="test">Test <input type="checkbox"></label>

And the following jQuery:

$("#test").click(function() {
    $(this).toggleClass("testClass");
});

When I click on the label I would expect the testClass class to be applied to that element (as it doesn't have that class when the page loads). However, nothing happens. See it for yourself here. I haven't tried it in IE, but it doesn't work correctly in Chrome or Firefox. I believe it will work in IE from the question linked to previously.

Stepping through the toggleClass method in the jQuery source, what seems to happen is the class gets added and removed again straight away.

If you move the input element outside of the label, the class is added as expected:

<label id="test" for="cb">Test</label>
<input type="checkbox" id="cb">

You can see that one in action here. So, my question is why does the first example not appear to add the class on the first click? Am I missing something blatantly obvious?

解决方案

It looks like the problem stems from the fact that the click event is being triggered twice (thus nullifying the toggle) when you have a nested input element. I haven't tested it on all browsers, but this seems to happen in FF8.

Try clicking on the label in this example: http://jsfiddle.net/cRnJS/

Apparently, clicks on label elements triggers a click event on its associated input (which is why the check/uncheck works) and this event bubbles upwards hence triggering it a second time in the parent label.

这篇关于带标签元素的toggleClass的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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