javascript jQuery off() 和 unbind() 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23961409/
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-10-28 01:53:42  来源:igfitidea点击:

What is the difference between jQuery off() and unbind()

javascriptjqueryjquery-events

提问by Andrew Evans

I was using jQuery .bind()and .unbind()to handle an animation event on scroll.

我正在使用 jQuery.bind().unbind()在滚动时处理动画事件。

$(window).bind('scroll', function(){
  ... code ...
  if(code_was_successful){
    $(window).unbind(e);
  }
});

As of 1.7 (I'm using 1.11) we're supposed to use .on()and .off(), but .off()seems to have no support for an event handler unbinding itself. For normal click events and such, I'd have to save the handler to a variable and set up another event handler to unbind it (which defeats the purpose), and for scroll events it's impossible since .off()requires a selector to unbind a specific handler, and scroll events can't have one.

从 1.7(我使用的是 1.11)开始,我们应该使用.on()and .off(),但.off()似乎不支持事件处理程序自行解除绑定。对于普通的点击事件等,我必须将处理程序保存到一个变量并设置另一个事件处理程序来解除它的绑定(这违背了目的),而对于滚动事件,这是不可能的,因为.off()需要选择器来解除绑定特定的处理程序,和滚动事件不能有一个。

What's the modern way to do this?

什么是现代方法来做到这一点?

回答by Felix Kling

What's the modern way to do this?

什么是现代方法来做到这一点?

Use a named function expression:

使用命名函数表达式

$(window).on('scroll', function handler(){
  ... code ...
  if(code_was_successful){
    $(window).off('scroll', handler);
  }
});

.off() requires a selector to unbind a specific handler

.off() 需要一个选择器来解除特定处理程序的绑定

No it does not. Just like .ondoesn't require a selector. You only need the selector if you want to unbind a delegated event handler.

不,不是的。就像.on不需要选择器一样。如果您想取消绑定委托的事件处理程序,您只需要选择器。

As you can read in the documentation of .offabout the selector argument:

正如您在关于选择器参数的文档中所.off读到的:

A selector which should match the one originally passed to .on() when attaching event handlers.

在附加事件处理程序时应该匹配最初传递给 .on() 的选择器。

So if you didn't use one in .on, you don't use one in .off.

所以如果你没有使用 one in .on,你就不要使用 one in .off

回答by Patrick Gunderson

you can use .on()and .off()like so:

你可以使用.on().off()喜欢这样:

function scrollHandler(e){
    if (myCondition) $(e.target).off('scroll', scrollHandler);
}

$(window).on('scroll', scrollHandler);