how to unbind all event using jquery

不打扰是莪最后的温柔 提交于 2019-11-26 17:59:48

问题


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 ?

thanks


回答1:


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

$('p').unbind();

From the docs:

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




回答2:


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

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:


@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).

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.



来源:https://stackoverflow.com/questions/3569393/how-to-unbind-all-event-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!