不过,你得需要把它做成一个组件的形式,这样才方便在各处调用,否则每一个页面都写一套,岂不是费力不讨好?
最好是实现一个这样的帮助类,如下所示:
//第一个参数是要分页的JSON对象 //第二个参数是每一页的最大项数 var helper = new PaginationHelper(['a','b','c','d','e','f'], 4); //总共多少页 => Math.ceil(6 / 4) helper.pageCount(); // 2 //总共多少项 => array.length helper.itemCount(); // 6 //求当前页的项数,这个页的索引是从0开始的 helper.pageItemCount(0); // 4 //6 - 4 = 2 helper.pageItemCount(1); // 2 //总共才2页,所以当前页无效,返回-1 helper.pageItemCount(2); // -1 //当前索引是属于第几页? helper.pageIndex(5); // 1 helper.pageIndex(2); // 0 //总共都才6条记录,所以20无效 helper.pageIndex(20); // -1 //索引小于0,无效返回-1 helper.pageIndex(-10); // -1
无论是前端分页还是后端分页,思路是一样的,都比较简单,不过得注意对非法值的处理。
function PaginationHelper(collection, itemsPerPage){ 
 this.collection = collection; 
 this.itemsPerPage = itemsPerPage; 
} 
 
PaginationHelper.prototype.itemCount = function() { 
 return this.collection.length; 
} 
 
PaginationHelper.prototype.pageCount = function() { 
 return Math.ceil(this.itemCount() / this.itemsPerPage); 
} 
 
PaginationHelper.prototype.pageItemCount = function(pageIndex) { 
 if(pageIndex < this.pageCount() - 1){ 
 return this.itemsPerPage; 
 } 
 else if(pageIndex == this.pageCount() - 1){ 
 return this.itemCount() - pageIndex * this.itemsPerPage; 
 } 
 else{ 
 return -1; 
 } 
} 
 
PaginationHelper.prototype.pageIndex = function(itemIndex) { 
 if(itemIndex >=0 && itemIndex < this.itemCount()){ 
 return Math.floor(itemIndex / this.itemsPerPage); 
 } 
 return -1; 
}下载本文