【问题标题】:event object for Throttle-debounceThrottle-debounce 的事件对象
【发布时间】:2013-11-17 22:42:04
【问题描述】:

我正在使用 Ben Alman 的 Throttle-debounce 插件。

当我这样调用 .throttle 时:

$(window).scroll($.throttle(250, function() {console.log(1)}));

节流函数触发。

但我必须检查是否未触发滚动事件。所以当我这样做时

$(window).scroll( function(event) {
    if (!event.isTrigger) {
        $.throttle(250, function() {console.log(1)});
        console.log(2);
    }
});

我只得到“2”的结果。由于某种原因,节流功能不会触发。 (第二次控制台打印是为了显示,该代码通过节流功能)

【问题讨论】:

    标签: javascript scroll jquery throttling


    【解决方案1】:

    我从未使用过 Ben 的插件,但似乎油门插件没有触发函数它返回一个每秒只能触发 x 次(或其他)的新函数。这是可行的,因为在 JS 中函数是一等对象,所以一个函数可以只返回一个新函数。

    所以如果你想让函数触发你需要调用它,

     var throttledFunc = $.throttle(250, function() {console.log(1)});
    
     $(window).scroll( function(event) {
        if (!event.isTrigger) {
           throttledFunc(event);
           console.log(2);
        }
      });
    

    你也可以重构你的第一个例子

     var throttledFunc = $.throttle(250, function() {console.log(1)});
    
     $(window).scroll(throttlesFunc);
    

    jquery 在内部获取您传入的函数引用,当滚动事件触发时,它会执行 throttlesFunc(event)

    【讨论】:

    • 非常感谢您的出色回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 2017-06-24
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多