当用.on()附加到文档时,不能删除特定的事件处理程序 [英] can't remove specific event handlers when attached to document with .on()

查看:94
本文介绍了当用.on()附加到文档时,不能删除特定的事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的小提琴演示我的情况...



http://jsfiddle.net/UnsungHero97/EM6mR/17/



我正在做的是为当前添加一个事件处理程序&安培;未来元素,使用 .on()。当某些事情发生时,我想要删除这些特定元素的事件处理程序;在小提琴的情况下,当选择单选按钮时,蓝色元素的事件处理程序应该被删除,并且点击这些元素不应再做任何事情。



它似乎没有工作:(



如何删除附加到我创建的文档的事件处理程序对于那些特定的蓝色元素, .on()

解决方案

您的 .on() .off()必须匹配。



这两个不匹配,所以 .off()调用将找不到要删除的匹配事件处理程序:

  $(document).on('click','.btn',function(){
update();
}) ;

$(document).off('click','.blue');

注意,选择器传递给 .on() .off()是不同的。 / p>




使用动态形式的 .on()(将选择器作为参数传递给.on()),您不能仅删除部分项目。这是因为在根元素上只安装了一个事件处理程序,而jQuery只能删除整个事物。所以,你不能只是 .off()一些动态项目。



你的选项是删除所有事件处理程序:

  $(document).off('click','.btn'); 

然后安装一个新的事件处理程序,排除您不需要的项目,例如: / p>

  $(document).off('click','.btn:not(.blue)'); 

或者,教会事件处理程序本身如何忽略 .blue 项目:

  $(document).on('click','.btn',function() 
if(!$(this).hasClass('blue')){
update();
}
});


Here's a simple fiddle to demo my situation...

http://jsfiddle.net/UnsungHero97/EM6mR/17/

What I'm doing is adding an event handler for current & future elements, using .on(). I want to be able to remove these event handlers for specific elements when something happens; in the case of the fiddle, when the radio button is selected, the event handler for the blue elements should be removed and clicking those elements should not do anything anymore.

It doesn't seem to be working :(

How do I remove the event handler attached to document that I created with .on() for those specific blue elements?

解决方案

The signature for your .on() and .off() has to match.

These two do not match so the .off() call won't find matching event handlers to remove:

$(document).on('click', '.btn', function() {
    update();
});

$(document).off('click', '.blue');

Note, the selector passed to .on() and .off() is different.


When using the dynamic form of .on() (where you pass a selector as an argument to .on()), you can't remove just part of the items. That's because there's only one event handler installed on the root element and jQuery can only remove the entire thing or not at all. So, you can't just .off() some of the dynamic items.

Your options are to remove all the event handlers with:

$(document).off('click', '.btn');

and, then install a new event handler that excludes the items you don't want such as:

$(document).off('click', '.btn:not(.blue)');

Or, teach the event handler itself how to ignore .blue items:

$(document).on('click', '.btn', function() {
    if (!$(this).hasClass('blue')) {
        update();
    }
});

这篇关于当用.on()附加到文档时,不能删除特定的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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