Infinite Scroll + .on()函数麻烦

问题描述 投票:0回答:1

我正在尝试通过“ inview”自定义事件(http://www.infinite-scroll.com/)触发来动态设置内容(通过Infinite Scroll脚本:https://github.com/protonet/jquery.inview设置样式)。

我的代码如下:

$(document).on("inview", ".attachment-portfoliosmall", function(e) {
    if( $.data( this, "styleappended" ) ) {
    return true;
    }
    $.data( this, "styleappended", true ); 
    $(".attachment-portfoliosmall").css('visibility','visible').hide().fadeIn('slow');
    $(".attachment-portfoliosmall").parent(".portfoliopreload").css("background", "none");
});

您可以清楚地看到,使用$ .data例程是为了确保对选择过滤器中的每个元素都不会多次执行.on()事件处理程序。

该代码在理论上非常有效,除了将下一页上动态加载的内容附加到文档上之后,.on()例程将第二次在每个单个元素上运行,而不仅仅是新添加的元素。

在我的网站上,如果滚动到下一页,您会看到所有元素逐渐淡出并再次变回,这是由.on()事件处理程序引起的。

如何防止它在上一页的先前处理的元素上执行?

javascript dynamic-data jquery infinite-scroll
1个回答
0
投票

这就是我在评论中的意思。

$(document).on("inview", ".attachment-portfoliosmall", function(e) {
    var $this = $(this);
    if(!$this.hasClass('loaded')) {
        $this.addClass('loaded'); 
        $this.css('visibility','visible').hide().fadeIn('slow');
        $this.parent(".portfoliopreload").css("background", "none");
    }
});

类似的方法可能对您有用。

© www.soinside.com 2019 - 2024. All rights reserved.