0

我正在为我的 tumblr 页面编写一个小jQueryjQuery.get()脚本,该脚本通过我想要从站点的下一页(它是一个tumblr站点,所以分页可以)的内容来模拟无限滚动加载。
我知道有一些无限滚动插件,但我尝试过的所有插件都不适合我,而且非常胖。我不需要所有的功能。该脚本会加载我想要的新元素,是的,但问题是每次都从两个页面加载内容。而且,显然,它应该只加载单个页面内容。

jQuery是 :

    $(document).ready(function() {
      "use strict";
      var nextPage = 2;
      var totalPages = {TotalPages};
      var url = '/page/'; // base url
      $(document).on('scroll', function() {
        if (nextPage <= totalPages) { // if exist new pages
          if ($(window).scrollTop()== $(document).height() - $(window).height()) { // when reach the page bottom
            $.get(url + nextPage, function(data){ // get the next page
              $(data).find(".post").appendTo(".posts"); // filter content we want and append it to the actual page element
              picturefill(); // reload picturefill,making the new images responsive
            });
            nextPage++; // increment nextpage counter
          };
        } else { // exit if no more pages
          return;
        }
      });
    });  

它加载的内容是:

<div class="posts">
<article class="photo-container post" id="{PostID}" data-reblog="{ReblogURL}">
    <div class=" picturefill" data-picture data-alt="" data-class="photo">
        <div class="picturefill" data-src="{PhotoURL-HighRes}" ></div>
        <div class="picturefill" data-src="{PhotoURL-500}" data-media="(max-width: 568px)"></div>
        <div class="picturefill" data-src="{PhotoURL-250}" data-media="(max-width: 250px)"></div>
        <img alt="" class="photo" src="http://img.jpg"> <!-- generated by picturefill -->
        <noscript><img class="photo" src="{PhotoURL-HighRes}" alt=""></noscript>
    </div>
    <!-- MORE CODE -->
</article>

我将Picturefill用于响应式图像,效果很好。有人有想法吗?谢谢。

4

1 回答 1

1

(在问题编辑中回答。转换为社区 wiki 答案。请参阅将问题的答案添加到问题本身时的适当操作是什么?

OP写道:

我使用控制变量解决了我的问题,lastLoadingPos该变量存储脚本插入页面内容的最后位置(相对于文档)。如果该位置没有改变,则不会进行插入。那是因为多次内容插入发生是因为脚本检测到页面底部已在同一位置多次到达。是的,这解决了问题,但我认为这不是正确的解决方案。只是一种解决方法。如果有人有任何想法,它会很受欢迎:D

我的解决方法(当然,我仍然需要添加一两件事):

$(document).ready(function() {
  "use strict";
  var nextPage = 2;
  var lastLoadingPos = 0; // stores last insertion position (document related)
  var totalPages = {TotalPages};
  var url = '/page/'; // base url
  $(document).on('scroll', function() {
    if (nextPage <= totalPages) { // if exist new pages
      var top = $(window).scrollTop();
      if ((lastLoadingPos != top) && (top== $(document).height() - $(window).height())) { // when current bottom position reached first time
        lastLoadingPos = top; // new last insertion position
        $.get(url + nextPage, function(data){ // get the next page
          $(data).find(".post").appendTo(".posts");  // filter wanted content
          picturefill(); // reload picturefill, making new images responsive
          nextPage++; // increment nextpage counter
        });
      }
    } else { // exit if no more pages
      return;
    }
  });
});  
于 2015-02-08T20:18:28.357 回答