123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- define(['jquery'], function ($) {
- var Pagination = function (options) {
- // 分页容器
- this.elem = $(options.elem || 'body');
- // 记录总数
- this.total = options.total || 0;
- // 每页显示最大记录数
- this.size = options.size || 10;
- // 当前页码
- this.number = options.number || 1;
- // 分页切换事件
- this.callback = options.callback || function (number) {
- console.info('current page is %d', number);
- };
- // 计算页码总数
- this.count = Math.ceil(this.total / this.size);
- if (this.count === 1) {
- this.elem.find('>.pagination').remove();
- return false;
- }
- // 初始化
- this.init();
- };
- Pagination.prototype = {
- // 初始化
- init: function () {
- // 追加分页到容器中
- this.elem.find('>.pagination').remove();
- this.elem.append('<div class="pagination"></div>');
- this.outer = this.elem.find('.pagination');
- this.renderPage();
- this.changePage();
- },
- firstPage: '<a href="javascript:;" title="首页" class="pagination_item gc_body_dw btn-page" to="f">首页</a>',
- prevPage: '<a href="javascript:;" title="上一页" class="pagination_item gc_body_dw btn-page" to="p">上一页</a>',
- nextPage: '<a href="javascript:;" title="下一页" class="pagination_item gc_body_dw btn-page" to="n">下一页</a>',
- lastPage: '<a href="javascript:;" title="尾页" class="pagination_item gc_body_dw btn-page" to="l">尾页</a>',
- renderPage: function () {
- this.outer.html('');
- if (this.number > 1) {
- this.outer.append(this.firstPage);
- this.outer.append(this.prevPage);
- }
- var start = this.number - 2;
- start = start < 1 ? 1 : start;
- var end = start + 5;
- if (end > this.count) {
- end = this.count + 1;
- start = end - 5 < 1 ? 1 : end - 5;
- }
- for (var i = start; i < end; i ++) {
- var cls = this.number === i ? ' active' : '';
- this.outer.append('<a href="javascript:;" title="第' + i + '页" class="pagination_item' + cls + '" to="' + i + '">' + i + '</a>');
- }
- if (end > 5 && start < this.count - 4) {
- this.outer.append('<a>...</a>');
- }
- if (this.number < this.count) {
- this.outer.append(this.nextPage);
- this.outer.append(this.lastPage);
- }
- },
- changePage: function () {
- this.outer.on('click', '.pagination_item', function (event) {
- var toPage = $(event.target).attr('to');
- switch (toPage) {
- case 'f':
- this.number = 1;
- break;
- case 'p':
- this.number -= 1;
- break;
- case 'n':
- this.number += 1;
- break;
- case 'l':
- this.number = this.count;
- break;
- default:
- if (this.number === toPage * 1) {
- return false
- }
- this.number = toPage * 1;
- }
- this.renderPage();
- this.callback(this.number);
- }.bind(this));
- }
- }
- return function (options) {
- new Pagination(options);
- };
- });
|