删除.clickable类后,仍会触发jQuery click() [英] jQuery click() still being triggered after .clickable class is removed

查看:98
本文介绍了删除.clickable类后,仍会触发jQuery click()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将click事件分配给特定类的div.发生点击时,该类将从div中移除.但是,您仍然可以单击div并触发click()事件(即使此类已被删除).这是一个示例:

I've got a click event assigned to a div of a particular class. When the click occurs, the class is removed from the div. However, you can still click the div and the click() event is triggered (even though the class has since been removed). Here's an example:

HTML:

<div class="clickable">
  <p>Click me</p>
</div>

JavaScript/jQuery:

$('.clickable').click(function() {
  $(this).removeClass('clickable');
  $(this).addClass('not-clickable');
  alert('Clicked!');
});

我可以看到已删除和添加了类(因为根据我的CSS更改了文本的颜色).但是,您仍然可以多次单击div,并且alert()仍会出现.

I can see the classes are removed and added (as the colour of the text changed as per my CSS). However, you are still able to click the div multiple times and the alert() will still appear.

这似乎也是相反的.因此,如果我将clickable类添加到div中,则$('.clickable').click(function() {...});中的代码将不会运行(但从外观上看,div会按照新样式更改).

This also seems to occur in reverse; so if I add the clickable class to a div, the code in $('.clickable').click(function() {...}); doesn't run (but visually, the div changes as per the new styles).

即使在jQuery添加/删除了clickable类之后,如何使点击事件与这些类匹配?

How can I make it so that the click events match up to the classes, even after jQuery adds/removes the clickable class?

推荐答案

将事件处理程序附加到DOM元素时,它保持不变. 类只是引用元素的一种方式,更改类不会取消绑定事件处理程序,因为您将必须手动取消绑定处理程序,并且如果使用jQuery 1.7+ on()off()是去:

When you attach an event handler to a DOM element, it stays intact. The class is just a way to reference the element, and changing the class will not unbind the event handlers, for that you will have to manually unbind the handler, and if using jQuery 1.7+ on() and off() is the way to go :

$('.clickable').on('click', function() {
  $(this).removeClass('clickable').addClass('not-clickable').off('click');
});

这将使该元素仅可单击一次,而您可以使用内置的one()函数来代替,因为这将在第一次单击后自动取消处理程序的绑定:

this would make the element clickable only once, and you could just use the built in one() function instead, as that will unbind the handler automagically after the first click :

$('.clickable').one('click', function() {
  $(this).removeClass('clickable').addClass('not-clickable');
});

这篇关于删除.clickable类后,仍会触发jQuery click()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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