jQuery off()和unbind()之间有什么区别 [英] What is the difference between jQuery off() and unbind()

查看:104
本文介绍了jQuery off()和unbind()之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery .bind()和.unbind()来处理滚动时的动画事件。

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

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

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

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.

现代的方法是什么?

推荐答案


现代的做法是什么?

What's the modern way to do this?

使用命名函数表达式

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




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

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

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

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

您可以在 .off 的文档:


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

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

因此,如果你没有在 .on 中使用一个,你就不要在 .off 中使用一个。

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

这篇关于jQuery off()和unbind()之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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