无限滚动问题多次追加元素

时间:2013-06-01 05:24:48

标签: javascript jquery scrolltop

$(function() {
  $(window).scroll(function(){
     checkY();
    });
 $('.post').last().after('<div class="newPost" />');
    var hrefArray = [],//array global
    hrefs = $('.paging a[href*="/t"]').not('.paging a[href*="/t"] > img');
 for(var i=0;i<hrefs.length;i++) {
     var hreflink = $(hrefs[i]).attr('href');
     hrefArray.push(hreflink);
     }
    hrefArray.pop();
    var postedLast = $('.post').last().position().top + $('.post').last().outerHeight();

function checkY(){
if(hrefArray.length > 1) {
   if( $(window).scrollTop() > postedLast){
         var url = hrefArray.shift();
           $('.newPost').html('<img  class="loadingImg" src="http://i79.servimg.com/u/f79/17/83/35/07/loadin10.gif"/>');
setTimeout(function() {
     $('.loadingImg').remove();
     $('.newPost').last().load(url+" .post",function() {
     //THIS LINE BELOW IS THE PROBLEM
     $('.newPost').last().after('<div class="newPost" />');
     postedLast = $('.post').last().position().top +
                  $('.post').last().outerHeight();
  });
 },3000);
  } 
 }
}
     window.onLoad = checkY();
 });

以上代码是Infinite Scroll的模拟。我的问题是它一遍又一遍地追加那条线。有没有办法让它只追加一次?我已经尝试了几乎所有这一切,它只是没有工作,所以永远。也有办法而不是这样做

 $('.post').last().position().top + $('.post').last().outerHeight();

因为它似乎不想及时加载。我想这样做,一旦元素在屏幕的底部,它就完成了这个功能。因为这个 - if( $(window).scrollTop() > postedLast){还有另外一种方法吗?因此,它不是位于屏幕顶部,而是在屏幕底部运行吗? (显然在最后)

1 个答案:

答案 0 :(得分:0)

检查出来:

http://www.jquery4u.com/tutorials/jquery-infinite-scrolling-demos/

我认为你可以利用一些好的开源插件,这些插件已经做了你想做的事情,而不必重新发明轮子,或者你可以使用他们的第二个例子中的这个片段(我发现它简单但有效),我在这里复制粘贴:

<script type="text/javascript">
$(window).scroll(function()
{
    if($(window).scrollTop() == $(document).height() - $(window).height())
    {
        $('div#loadmoreajaxloader').show();
        $.ajax({
        url: "loadmore.php",
        success: function(html)
        {
            if(html)
            {
                $("#postswrapper").append(html);
                $('div#loadmoreajaxloader').hide();
            }else
            {
                $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
            }
        }
        });
    }
});
</script>