所以我正在读取一个本地 json 文件,其中包含 {[Object,Object,Object.....]} 我正在使用
$.getJSON('products.json', function (pdata) {
for (var i = 0; i < pdata.data.length; i++) {
AppendtoDom(pdata.data[i]);
}
上面的代码读取 json 对象并附加到 DOM,但我想最初一次只加载 100 个对象,并在滚动时保持附加。
假设有大约 1200 个对象。我该怎么办?
到目前为止我的实现
$(function(){
loadData();
});
function loadData(){
$.getJSON('products.json', function (pdata) {
var i = 0;
function addtoDom(num){
var limit = Math.min(i + num, pdata.data.length);
for(; i < limit; i++){
getInformation(pdata.data[i]);
}
}
addtoDom(100);
$('.content').jscroll({
callback: addtoDom(100)
});
});
}
function getInformation(obj){
var content = "";
for (var i = 0; i < 4; i++) {
content += '<li>';
content += "<img src='" + obj.imageUrl + "' style='width:200px;height:200px'/>";
content += '<div class="productName">' + obj.fullName + "</div>";
content += '<div class="price">Price: ' + obj.price + "</div>";
content += '</li>';
}
$("<ul class= 'view'>" + content + "</ul>").appendTo('.content');
}
我在 How would i implement an infinite scroll in my DOM 中问过类似的问题
最佳答案
您可以将从 Ajax 调用返回的所有对象放入持久变量中,将前 100 个添加到 DOM,保留到目前为止添加的数量的计数器,然后滚动到某个点时,再添加 100 个,再添加 100 个,依此类推。
$.getJSON('products.json', function (pdata) {
var i = 0;
function addMore(num) {
var limit = Math.min(i + num, pdata.data.length);
for (; i < limit; i++) {
AppendtoDom(pdata.data[i]);
}
}
// add the first 100
addMore(100);
// then set up whatever scroll detection you want here and
// when you decide that it has scrolled enough to add some more
// you just call addMore(100) again
});
<小时/>
在您具体实现上述想法时,您遇到了实现错误。您必须为回调传递函数引用,因此请更改此:
$('.content').jscroll({
callback: addtoDom(100)
});
对此:
$('.content').jscroll({
callback: function() {addtoDom(100);}
});
关于javascript - JSON 对象(如何最初不将整个对象加载到 DOM 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28757036/