【问题标题】:javascript / jquery - avoid repeating evaluation of a conditionaljavascript / jquery - 避免重复评估条件
【发布时间】:2012-08-31 10:59:07
【问题描述】:

我目前在 jquery 的滚动事件中有一个条件运行,这似乎没有多大意义,因为它只会执行一次。我想知道是否有任何方法可以确保条件只会被评估一次。

这是我的代码:

$window.scroll(function() {
  if (s1_doAnimate == true){
    s1_doAnimate = false;
  }
})

【问题讨论】:

  • 这是滚动事件中代码的一部分还是唯一的操作?

标签: javascript events scroll jquery


【解决方案1】:

使用$.one

$(window).one('scroll', function(){
...
});

【讨论】:

    【解决方案2】:

    一旦满足条件,您可以取消绑定处理程序;

    $window.scroll(function foo /* give the function a name */ () {
      if (s1_doAnimate == true){
        s1_doAnimate = false;
    
        // Unbind the handler referenced by the name...
        $window.off(foo);
      }
    })
    

    【讨论】:

    • 这不会为每个触发器创建一个新函数吗?也许将foo 存储在处理程序之外会更好?只是好奇...
    • @David:不,声明只处理一次(函数表达式被传递给scroll()函数之前)。 IE more);
    猜你喜欢
    • 2011-04-03
    • 2014-07-06
    • 2014-06-13
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    相关资源
    最近更新 更多