javascript - 函数完成后如何删除滚动事件

标签 javascript jquery performance

我将一个滚动事件监听器附加到包装 div,然后对于具有“js-chart”类的每个 div,它将检查该特定 js-chart 是否在 View 内,并将在其上执行函数。然后,它将从该元素中删除 js-chart 类,以便它不会继续触发该函数。

这一切都工作正常,但我想做的是,当所有 js-charts 都被触发时(因此 js-chart 中不再有元素),要完全删除滚动事件监听器,所以我我不会一直进行毫无意义的检查。

$('#wrapper').scroll(function() {

        var $wrapper = $(this);

        $('.js-chart').each( function (n) {

            var $this = $(this);

            if ( $this.position().top + $this.height() > 100 && $this.position().top < $wrapper.height() ) {
                console.log("Test");
                createChart($this);
                $this.removeClass('js-chart');

            }
        });

    });

最佳答案

添加如下内容:

$('#wrapper').on("scroll", function() {
    var $wrapper = $(this);

    $('.js-chart').each( function (n) {
        var $this = $(this);
        if ( $this.position().top + $this.height() > 100 && $this.position().top < $wrapper.height() ) {
            console.log("Test");
            createChart($this);
            $this.removeClass('js-chart');
        }
    });

    if (!$('.js-chart').length) {
        $wrapper.off("scroll");
    }
});

关于javascript - 函数完成后如何删除滚动事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28550887/

相关文章:

javascript - jQuery Ajax 显示传入的数据

javascript - 如何选择范围之间的元素?

javascript - 选择 Kendo UI ListView 项

javascript - Modernizr.load (Yepnope) 是否用于 <head>

vb.net - 检查两个列表是否至少有一个共同项

java - 自动检测 Java 中存在潜在性能问题的循环

Javascript:数组和 For 循环基础知识

javascript - ESLint 提示 TypeScript 类型声明在声明之前就使用了类型

javascript - JS - 从嵌套在应该可点击的元素中的元素取消绑定(bind)点击操作

javascript - 对两个数组的值进行分组(平均)