使用此代码,我得到了我的JSON数组的前2个结果。如何通过滚动来“加载更多”?
function suchen() {
var suche = document.getElementById("mysearch").value;
$.ajax({
url: 'http://XXX.de/?apikey=XXX&search=' + suche + '&callback=?',
type: "GET",
dataType: 'json',
success: function daten (response) {
$( 'ul#suche li' ).remove();
var i = 0;
response.forEach(function(data) {
if(i >= 2)
return false;
$('ul#suche').append('<li class="item-content"><div class="item-inner"><div class="item-title">' + data.title + '</div></div></li>');
i++;
})
}
});
}
如何通过滚动来加载下一个(例如3-4个)项目?
答案 0 :(得分:0)
在此之前,我要提一下,如果在选择器中使用id
,则无需指定节点类型。
我的意思是使用$('#suche')
代替$('ul#suche')
当谈到无限滚动时,你应该在你的ajax调用中明确指定项目数量,以获得你需要的精确数据块。如果你的API有可能,可以指定from
和amount
。
像这样:
var from = 0
var amount = 2
var callApi = function (from, amount) {
$.ajax({
url: 'http://XXX.de/?apikey=XXX&search=' + suche + '&from' + from + '&amount=' + amount + '&callback=?',
success: function (response) {
response.forEach(function(data) {
$('#suche').append(
'<li class="item-content">' +
'<div class="item-inner">' +
'<div class="item-title">' + data.title + '</div>' +
'</div>' +
'</li>'
);
});
// increase from on each call
from += amount;
}
});
};
// call it
callApi(from, amount);
然后你需要添加scroll
eventListener,当最后一个元素出现在窗口画布上时,再次调用它。
var lastChild, lastChildPosition, bottomPosition, bottomPosition
$(document).on('scroll', function (e) {
lastChild = $('#suche li:last-child');
lastChildPosition = lastChild.scrollTop();
scrollTop = $(this).scrollTop();
bottomPosition = scrollTop + $(window).height();
// call it again
if (bottomPosition > lastChildPosition) {
callApi(from, amount);
}
})
答案 1 :(得分:0)
非常感谢你。我尝试用Wordpress构建一个基于你的想法的版本:
function suchen_api(lastindex) {
var suche = document.getElementById("mysearch").value;
var offset = lastindex;
var showposts = 2;
$.ajax({
url: 'http://XXX.de/?apikey=XXX&search=' + suche + '&offset=' + offset + ' &showposts=' + showposts + '&callback=?',
type: "GET",
dataType: 'json',
success: function(response){
response.forEach(function(data) {
$('ul#suche').append('<li class="item-content"><div class="item-inner"><div class="item-title">' + data.title + '</div></div></li>');
myApp.hideIndicator(); // Preloader geht aus
$$('.infinite-scroll-preloader').remove();
})
}
});
}
function suchen() {
$( '#suche li' ).remove();
var startindex = 0;
suchen_api(startindex);
}
// on Scroll
$$('.infinite-scroll').on('infinite', function () {
var startindex = $("ul#suche li").length;
suchen_api(startindex);
})
只有一个问题。有时它会告诉我最后一个加倍。你有什么想法吗?