jQuery 如何使用jquery取消绑定所有事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3569393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:41:20  来源:igfitidea点击:

how to unbind all event using jquery

jqueryeventsunbind

提问by zjm1126

i can use this code to remove click event,

我可以使用此代码删除点击事件,

$('p').unbind('click')

but , has some method to remove all event ?

但是,有一些方法可以删除所有事件吗?

has a method named unbindAllin jquery ?

有一个unbindAll在 jquery 中命名的方法?

thanks

谢谢

回答by Nick Craver

You can call .unbind()without parameters to do this:

您可以.unbind()不带参数调用来执行此操作:

$('p').unbind();

From the docs:

文档

In the simplest case, with no arguments, .unbind()removes all handlers attached to the elements.

在最简单的情况下,没有参数,.unbind()删除所有附加到元素的处理程序。

回答by totallyNotLizards

As of jQuery 1.7, off()and on()are the preferred methods to bind and unbind event handlers.

从 jQuery 1.7 开始,off()on()是绑定和解除绑定事件处理程序的首选方法。

So to remove all handlers from an element, use this:

因此,要从元素中删除所有处理程序,请使用以下命令:

$('p').off();

or for specific handlers:

或对于特定处理程序:

$('p').off('click hover');

And to add or bind event handlers, you can use

并添加或绑定事件处理程序,您可以使用

$('p').on('click hover', function(e){
    console.log('click or hover!');
});

回答by Blue Raspberry

@jammypeach is right about on & off being the accepted methods to use. Unbind sometimes ends up creating weird behaviors (e.g. not actually unbinding events correctly).

@jammypeach 关于打开和关闭是公认的使用方法是正确的。解除绑定有时最终会产生奇怪的行为(例如,实际上并未正确解除绑定事件)。

To unbind all elements within the body, find them all and for each one turn off the click handler (what was the old unbind):

要取消绑定正文中的所有元素,请找到所有元素并为每个元素关闭点击处理程序(旧的取消绑定是什么):

$("body").find("*").each(function() {
    $(this).off("click");
});

Also see how to save the events that you've turned off in this stack overflow question.

另请参阅如何保存您在此堆栈溢出问题中关闭的事件。