[英]Using array.splice and calculating boundaries javascript json ajax
因此,我通過ajax接收到json文件並將其顯示在表格中。 我想對數組進行分頁。 所以這就是我在做什么
function Paginator(groups){
/**
* This should work.
* The children() function returns a JQuery object that contains the children.
* So you just need to check the size and see if it has at least one child.
* #grouplist > * makes it slightly faster - I think...
*/
if ( $('#grouplist > *').length > 0 ) {
$.each($('#grouplist').children(), function(i, current) {
current.remove();
});
}
//http://davidwalsh.name/javascript-clone-array
var clone_group = groups.slice(0);
var page = _globalpage,
startRec = Math.max(page - 1, 0) * _recPerPage,
endRec = Math.min(startRec + _recPerPage, clone_group.length)
recordsToShow = clone_group.splice(startRec, endRec);
console.log('start '+startRec+' end '+endRec+' page '+ page + ' records to show '+recordsToShow.length);
// loop through the array to populate your list
$.each(recordsToShow, function(i, currentGroup){
console.log('id '+currentGroup.id);
$('#grouplist').append('<tr> /*html with stuff I need*/ </tr>');
});
}
可能不是很好的做法,但是每個以下划線“ _”開頭的變量都是全局定義的。 唯一更改的是_globalpage,每次您單擊“上一個”或“下一個”時,_globalpage都會遞增或遞減1。 一旦我讓它正常工作,我就打算將其更改為cookie。
這是來自console.log的結果
“ 開始0結束10頁面1記錄顯示10 ”
從“ id 1 ”到“ id 10 ”
下一個之后
“ 開始10結束20頁面2記錄顯示20 ”
“ id 11 ”到“ id 30 ”
這怎么了 提前致謝
解決了。 我通常會在發布之前弄清楚這個問題……XP甚至不需要克隆數組,我所需要的只是使用array.slice而不是array.splice
解:
var page = _globalpage,
startRec = Math.max(page - 1, 0) * _recPerPage,
endRec = Math.min(startRec + _recPerPage, groups.length)
recordsToShow = groups.slice(startRec, endRec);
$.each(recordsToShow, function(i, currentGroup){ //print stuff
無論如何,感謝互聯網的集體精神甚至在幕后提供了幫助。 :P
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.