JavaScript趣题:前端分页

黄舟
黄舟 原创
2017-01-22 14:52:44 1250浏览

在前端进行分页是一件很炫酷的事情,它可以缓解服务器端的压力,减少了请求次数以及服务器计算量。

不过,你得需要把它做成一个组件的形式,这样才方便在各处调用,否则每一个页面都写一套,岂不是费力不讨好?

最好是实现一个这样的帮助类,如下所示:

//第一个参数是要分页的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;  
}

以上就是JavaScript趣题:前端分页的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。