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('
'); this.outer = this.elem.find('.pagination'); this.renderPage(); this.changePage(); }, firstPage: '首页', prevPage: '上一页', nextPage: '下一页', lastPage: '尾页', 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('' + i + ''); } if (end > 5 && start < this.count - 4) { this.outer.append('...'); } 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); }; });