源码如下:
- $.fn.pager = function (pagerInfo) {
- var recordCount = this.size();
- if (recordCount <= pagerInfo.pagesize) return;
- var currentPageIndex = 1, //当前面,默认为1
- pageCount = Math.ceil(recordCount / pagerInfo.pagesize); //总页数
- //构建分页的html
- $('<div>一共' + this.size() + '条记录,一共' + pageCount + '页,当前第<span>1</span>页</div>')
- .insertAfter(pagerInfo.container)
- .append($('<a class="prev-page">上一页</a>').click(function () {
- if (currentPageIndex == 1) return;
- currentPageIndex--;
- showRecords(currentPageIndex);
- $(this).prev('span').text(currentPageIndex);
- }))
- .append($('<a class="prev-page" href>下一页</a>').click(function () {
- if (currentPageIndex == pageCount) return;
- currentPageIndex++;
- showRecords(currentPageIndex);
- $(this).prevAll('span').text(currentPageIndex);
- }))
- .css(pagerInfo.css)
- .find('span').css({ padding: 0 });
- var jRecords = this; //保留作用域
- //pageIndex以1为开始
- var showRecords = function (pageIndex) {
- jRecords.hide(); //隐匿所有记录先
- var startIndex = (pageIndex - 1) * pagerInfo.pagesize, //当前页的开始记录
- endIndex = (pageIndex * pagerInfo.pagesize) - 1; //当前页的结束记录
- jRecords.filter(':eq(' + startIndex + '),:gt(' + startIndex + ')').show(); //显示大于开始记录(包含)的所有记录
- jRecords.filter(':gt(' + endIndex + ')').hide(); //隐藏大于结束记录的所有记录,以达到分页效果
- };
- showRecords(currentPageIndex);
- };
使用举例:
- $('#feedback ul li') //数据源
- .pager({
- pagesize: 10, //分页大小
- container: $('#feedback'), //容纳分页html的容器
- css: { 'margin-left': '40px'} //分页html的样式
- });