我正在爲我的tumblr頁面寫一點jQuery腳本,模擬通過jQuery.get()
我想從下一頁中獲得的無限滾動加載的網站(這是一個tumblr網站,所以分頁是確定的)。
我知道有一些無限的滾動插件,但我所有的嘗試都不適合我,除此之外,它們非常肥膩。我不需要所有的功能。 該腳本加載了我想要的新元素,是的,但問題是每次都從兩個頁面加載內容。而且,顯然,它應該只加載一個頁面內容。用jQuery無限滾動腳本加載兩頁內容(只需要一個加載時)
的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爲響應圖像和效果很好。 有人有想法嗎?謝謝。
了'scroll'事件可能是多次觸發,導致Ajax'$ .get()'也被觸發多次。您應該添加一個變量,以防止自己獲取另一個頁面,直到當前的Ajax請求完成。另外,你應該在Ajax回調中增加'nextPage ++'*。 – Felix 2013-02-13 13:05:40
哦。謝謝@FelixBonkoski。我現在看到你的評論。我昨晚來到了相同的解決方案。這是相當晚,所以我想今天更新這個(開始寫午餐之前,現在完成,沒有反感,抱歉)。 我會像你明智地建議的那樣改變增量位置。很多人都很感謝答案:D – soulchainer 2013-02-13 15:22:05