i can use this code to remove click event,
我可以用这个代码来移除点击事件,
$('p').unbind('click')
but , has some method to remove all event ?
但是,有一些方法可以删除所有事件吗?
has a method named unbindAll
in jquery ?
在jquery中有一个名为unbindAll的方法吗?
thanks
谢谢
3 个解决方案
#1
#2
70
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!');
});
#3
1
@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是正确的关于&关闭是被接受的方法使用。Unbind有时会产生奇怪的行为(例如,没有正确地取消绑定事件)。
To unbind all elements within the body, find them all and for each one turn off the click handler (what was the old unbind):
要解开身体内所有的元素,找到它们的全部,并且每一个都关闭点击处理程序(旧的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.
还可以看到如何保存在这个堆栈溢出问题中已经关闭的事件。
#1
84
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()删除所有附加到元素的处理程序。
#2
70
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!');
});
#3
1
@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是正确的关于&关闭是被接受的方法使用。Unbind有时会产生奇怪的行为(例如,没有正确地取消绑定事件)。
To unbind all elements within the body, find them all and for each one turn off the click handler (what was the old unbind):
要解开身体内所有的元素,找到它们的全部,并且每一个都关闭点击处理程序(旧的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.
还可以看到如何保存在这个堆栈溢出问题中已经关闭的事件。