mricode.pagination.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /*!
  2. * Mricode Pagination Plugin
  3. * Github: https://github.com/mricle/Mricode.Pagination
  4. * Version: 1.4.4
  5. *
  6. * Required jQuery
  7. *
  8. * Copyright 2016 Mricle
  9. * Released under the MIT license
  10. */
  11. (function (factory) {
  12. if (typeof define === 'function' && define.amd) {
  13. // AMD
  14. define(['jquery'], factory);
  15. } else if (typeof exports === 'object') {
  16. // Node / CommonJS
  17. factory(require('jquery'));
  18. } else {
  19. // Globals
  20. factory(jQuery);
  21. }
  22. })(function ($) {
  23. "use strict";
  24. var Page = function (element, options) {
  25. var defaultOption = {
  26. pageIndex: 0,
  27. pageSize: 10,
  28. total: 0,
  29. pageBtnCount: 11,
  30. showFirstLastBtn: true,
  31. firstBtnText: null,
  32. lastBtnText: null,
  33. prevBtnText: "«",
  34. nextBtnText: "»",
  35. loadFirstPage: true,
  36. remote: {
  37. url: null,
  38. params: null,
  39. pageParams: null,
  40. success: null,
  41. beforeSend: null,
  42. complete: null,
  43. pageIndexName: 'pageIndex',
  44. pageSizeName: 'pageSize',
  45. totalName: 'total',
  46. traditional: false
  47. },
  48. pageElementSort: ['$page', '$size', '$jump', '$info'],
  49. showInfo: false,
  50. infoFormat: '{start} ~ {end} of {total} entires',
  51. noInfoText: '0 entires',
  52. showJump: false,
  53. jumpBtnText: 'Go',
  54. showPageSizes: false,
  55. pageSizeItems: [5, 10, 15, 20],
  56. debug: false
  57. }
  58. this.$element = $(element);
  59. this.$page = $('<ul class="m-pagination-page"></ul>').hide();
  60. this.$size = $('<div class="m-pagination-size"></div>').hide();
  61. this.$jump = $('<div class="m-pagination-jump"></div>').hide();
  62. this.$info = $('<div class="m-pagination-info"></div>').hide();
  63. this.options = $.extend(true, {}, defaultOption, $.fn.pagination.defaults, options);
  64. if (options.pageElementSort) {
  65. this.options.pageElementSort = options.pageElementSort
  66. } else {
  67. if ($.fn.pagination.defaults && $.fn.pagination.defaults.pageElementSort) {
  68. this.options.pageElementSort = $.fn.pagination.defaults.pageElementSort;
  69. } else {
  70. this.options.pageElementSort = defaultOption.pageElementSort;
  71. }
  72. }
  73. this.options.pageSizeItems = options.pageSizeItems || (($.fn.pagination.defaults && $.fn.pagination.defaults.pageSizeItems) ? $.fn.pagination.defaults.pageSizeItems : defaultOption.pageSizeItems);
  74. this.total = this.options.total;
  75. this.currentUrl = this.options.remote.url;
  76. this.currentPageIndex = utility.convertInt(this.options.pageIndex);
  77. this.currentPageSize = utility.convertInt(this.options.pageSize);
  78. this.currentParams = utility.deserializeParams(this.options.remote.params) || {};
  79. this.getLastPageNum = function () {
  80. return pagination.core.calLastPageNum(this.total, this.currentPageSize);
  81. }
  82. if (this.options.remote.success === null) {
  83. this.options.remote.success = this.options.remote.callback;
  84. }
  85. this.init();
  86. }
  87. Page.prototype = {
  88. getPageIndex: function () {
  89. return this.currentPageIndex;
  90. },
  91. getPageSize: function () {
  92. return this.currentPageSize;
  93. },
  94. getParams: function () {
  95. return this.currentParams;
  96. },
  97. setPageIndex: function (pageIndex) {
  98. if (pageIndex !== undefined && pageIndex !== null) {
  99. this.currentPageIndex = utility.convertInt(pageIndex);
  100. }
  101. },
  102. setPageSize: function (pageSize) {
  103. if (pageSize !== undefined && pageSize !== null) {
  104. this.currentPageSize = utility.convertInt(pageSize);
  105. }
  106. },
  107. setRemoteUrl: function (url) {
  108. if (url) {
  109. this.currentUrl = url;
  110. }
  111. },
  112. setParams: function (params) {
  113. if (params) {
  114. this.currentParams = utility.deserializeParams(params);
  115. }
  116. },
  117. render: function (total) {
  118. if (total !== undefined && total !== null) {
  119. this.total = utility.convertInt(total);
  120. }
  121. this.renderPagination();
  122. this.debug('pagination rendered');
  123. },
  124. init: function () {
  125. this.initHtml();
  126. this.initEvent();
  127. if (this.currentUrl && this.options.loadFirstPage) {
  128. this.remote();
  129. } else {
  130. this.renderPagination();
  131. }
  132. this.debug('pagination inited');
  133. },
  134. initHtml: function () {
  135. //init size module
  136. var sizeHtml = $('<select data-page-btn="size"></select>');
  137. for (var i = 0; i < this.options.pageSizeItems.length; i++) {
  138. sizeHtml.append('<option value="' + this.options.pageSizeItems[i] + '" ' + (this.currentPageSize == this.options.pageSizeItems[i] ? "selected" : "") + ' >' + this.options.pageSizeItems[i] + '</option>')
  139. }
  140. sizeHtml.val(this.currentPageSize);
  141. this.$size.append(sizeHtml);
  142. //init jump module
  143. var jumpHtml = '<div class="m-pagination-group"><input data-page-btn="jump" type="text"><button data-page-btn="jump" type="button">' + this.options.jumpBtnText + '</button></div>';
  144. this.$jump.append(jumpHtml);
  145. for (var i = 0; i < this.options.pageElementSort.length; i++) {
  146. this.$element.append(this[this.options.pageElementSort[i]]);
  147. }
  148. },
  149. initEvent: function () {
  150. this.$element
  151. .on('click', { page: this }, function (event) {
  152. if ($(event.target).is('button')) {
  153. if ($(event.target).data('pageBtn') == 'jump') {
  154. var $input = event.data.page.$element.find('input[data-page-btn=jump]');
  155. event.data.page.jumpEventHandler($input.val(), event);
  156. }
  157. } else {
  158. if ($(event.target).data('pageIndex') !== undefined)
  159. eventHandler.call(event.data.page, event);
  160. }
  161. }).on('change', { page: this }, function (event) {
  162. var $this = $(event.target);
  163. if ($this.data('pageBtn') == 'jump') {
  164. event.data.page.jumpEventHandler($this.val(), event);
  165. }
  166. if ($this.data('pageBtn') == 'size') {
  167. eventHandler.call(event.data.page, event);
  168. }
  169. }).on('keypress', { page: this }, function (event) {
  170. if (event.keyCode == "13") {
  171. var $input = event.data.page.$element.find('input[data-page-btn=jump]')
  172. event.data.page.jumpEventHandler($input.val(), event);
  173. }
  174. });
  175. this.$element.find('input[data-page-btn=jump]').on('blur', {
  176. page: this
  177. }, function(event){
  178. event.stopPropagation();
  179. var pageIndex = $(this).val();
  180. event.data.page.jumpEventHandler($(this).val(), event);
  181. $(this).val(pageIndex)
  182. })
  183. },
  184. jumpEventHandler: function (inputValue, event) {
  185. if (!inputValue) {
  186. this.$jump.removeClass('error');
  187. } else if (!pagination.check.checkJumpPage(inputValue)) {
  188. this.$jump.addClass('error');
  189. }
  190. else if (utility.convertInt(inputValue) > this.getLastPageNum()) {
  191. this.$jump.addClass('error');
  192. }
  193. else {
  194. this.$jump.removeClass('error');
  195. eventHandler.call(this, event);
  196. }
  197. },
  198. doPagination: function () {
  199. if (this.currentUrl) {
  200. this.remote();
  201. } else {
  202. this.renderPagination();
  203. }
  204. },
  205. remote: function () {
  206. if (typeof this.options.remote.pageParams === 'function') {
  207. var pageParams = this.options.remote.pageParams.call(this, { pageIndex: this.currentPageIndex, pageSize: this.currentPageSize });
  208. this.currentParams = $.extend({}, this.currentParams, pageParams);
  209. } else {
  210. this.currentParams[this.options.remote.pageIndexName] = this.currentPageIndex;
  211. this.currentParams[this.options.remote.pageSizeName] = this.currentPageSize;
  212. }
  213. pagination.remote.getAjax(this, this.currentUrl, this.currentParams, this.ajaxCallBack, this.options.remote.beforeSend, this.options.remote.complete,this.options.remote.traditional);
  214. },
  215. ajaxCallBack: function (result) {
  216. var total = utility.mapObjectNameRecursion(result, this.options.remote.totalName);
  217. if (total == null || total == undefined)
  218. throw new Error("the response of totalName : '" + this.options.remote.totalName + "' not found.");
  219. total = utility.convertInt(total);
  220. this.total = total;
  221. var lastPageNum = this.getLastPageNum();
  222. if (this.currentPageIndex > 0 && lastPageNum - 1 < this.currentPageIndex) {
  223. this.setPageIndex(lastPageNum - 1);
  224. this.remote();
  225. } else {
  226. if (typeof this.options.remote.success === 'function') this.options.remote.success(result);
  227. this.renderPagination();
  228. }
  229. },
  230. onEvent: function (eventName, pageIndex, pageSize) {
  231. if (pageIndex != null) this.currentPageIndex = utility.convertInt(pageIndex);
  232. if (pageSize != null) this.currentPageSize = utility.convertInt(pageSize);
  233. this.doPagination();
  234. this.$element.trigger(eventName, {
  235. pageIndex: this.currentPageIndex, pageSize: this.currentPageSize
  236. });
  237. this.debug('pagination ' + eventName);
  238. },
  239. //生成分页
  240. renderPagination: function () {
  241. var option = {
  242. showFirstLastBtn: this.options.showFirstLastBtn,
  243. firstBtnText: this.options.firstBtnText,
  244. prevBtnText: this.options.prevBtnText,
  245. nextBtnText: this.options.nextBtnText,
  246. lastBtnText: this.options.lastBtnText
  247. }
  248. var lastPageNum = this.getLastPageNum();
  249. this.currentPageIndex = lastPageNum > 0 && this.currentPageIndex > lastPageNum - 1 ? lastPageNum - 1 : this.currentPageIndex;
  250. this.$page.empty().append(pagination.core.renderPages(this.currentPageIndex, this.currentPageSize, this.total, this.options.pageBtnCount, option)).show();
  251. if (this.options.showPageSizes && lastPageNum !== 0) this.$size.show(); else this.$size.hide();
  252. if (this.options.showJump && lastPageNum !== 0) this.$jump.show(); else this.$jump.hide();
  253. this.$info.text(pagination.core.renderInfo(this.currentPageIndex, this.currentPageSize, this.total, this.options.infoFormat, this.options.noInfoText));
  254. if (this.options.showInfo) this.$info.show(); else this.$info.hide();
  255. },
  256. //销毁分页
  257. destroy: function () {
  258. this.$element.unbind().data("pagination", null).empty();
  259. this.debug('pagination destroyed');
  260. },
  261. debug: function (message, data) {
  262. if (this.options.debug && console) {
  263. message && console.info(message + ' : pageIndex = ' + this.currentPageIndex + ' , pageSize = ' + this.currentPageSize + ' , total = ' + this.total);
  264. data && console.info(data);
  265. }
  266. }
  267. }
  268. var eventHandler = function (event) {
  269. var that = event.data.page;
  270. var $target = $(event.target);
  271. if (event.type === 'click' && $target.data('pageIndex') !== undefined && !$target.parent().hasClass('active')) {
  272. that.onEvent(pagination.event.pageClicked, $target.data("pageIndex"), null);
  273. }
  274. else if ((event.type === 'click' || event.type === 'keypress') && $target.data('pageBtn') === 'jump') {
  275. var pageIndexStr = that.$jump.find('input').val();
  276. if (utility.convertInt(pageIndexStr) <= that.getLastPageNum()) {
  277. that.onEvent(pagination.event.jumpClicked, pageIndexStr - 1, null);
  278. that.$jump.find('input').val(null);
  279. }
  280. }
  281. else if (event.type === 'change' && $target.data('pageBtn') === 'size') {
  282. var newPageSize = that.$size.find('select').val();
  283. var lastPageNum = pagination.core.calLastPageNum(that.total, newPageSize);
  284. if (lastPageNum > 0 && that.currentPageIndex > lastPageNum - 1) {
  285. that.currentPageIndex = lastPageNum - 1;
  286. }
  287. that.onEvent(pagination.event.pageSizeChanged, that.currentPageIndex, newPageSize);
  288. } else if (event.type === 'blur'){
  289. var pageIndexStr = that.$jump.find('input').val();
  290. if (utility.convertInt(pageIndexStr) <= that.getLastPageNum()) {
  291. that.onEvent(pagination.event.jumpClicked, pageIndexStr - 1, null);
  292. that.$jump.find('input').val(null);
  293. }
  294. }
  295. };
  296. var pagination = {};
  297. pagination.event = {
  298. pageClicked: 'pageClicked',
  299. jumpClicked: 'jumpClicked',
  300. pageSizeChanged: 'pageSizeChanged'
  301. };
  302. pagination.remote = {
  303. getAjax: function (pagination, url, data, success, beforeSend, complate,traditional) {
  304. $.ajax({
  305. url: url,
  306. dataType: 'json',
  307. data: data,
  308. cache: false,
  309. traditional:traditional,
  310. contentType: 'application/Json',
  311. beforeSend: function (XMLHttpRequest) {
  312. if (typeof beforeSend === 'function') beforeSend.call(this, XMLHttpRequest);
  313. },
  314. complete: function (XMLHttpRequest, textStatue) {
  315. if (typeof complate === 'function') complate.call(this, XMLHttpRequest, textStatue);
  316. },
  317. success: function (result) {
  318. success.call(pagination, result);
  319. }
  320. })
  321. }
  322. };
  323. pagination.core = {
  324. /*
  325. options : {
  326. showFirstLastBtn
  327. firstBtnText:
  328. }
  329. */
  330. renderPages: function (pageIndex, pageSize, total, pageBtnCount, options) {
  331. options = options || {};
  332. var pageNumber = pageIndex + 1;
  333. var lastPageNumber = this.calLastPageNum(total, pageSize);
  334. var html = [];
  335. if (lastPageNumber <= pageBtnCount) {
  336. html = this.renderGroupPages(1, lastPageNumber, pageNumber);
  337. }
  338. else {
  339. var firstPage = this.renderPerPage(options.firstBtnText || 1, 0);
  340. var lastPage = this.renderPerPage(options.lastBtnText || lastPageNumber, lastPageNumber - 1);
  341. //button count of both sides
  342. var symmetryBtnCount = (pageBtnCount - 1 - 4) / 2;
  343. if (!options.showFirstLastBtn)
  344. symmetryBtnCount = symmetryBtnCount + 1;
  345. var frontBtnNum = (pageBtnCount + 1) / 2;
  346. var behindBtnNum = lastPageNumber - ((pageBtnCount + 1) / 2);
  347. var prevPage = this.renderPerPage(options.prevBtnText, pageIndex - 1);
  348. var nextPage = this.renderPerPage(options.nextBtnText, pageIndex + 1);
  349. symmetryBtnCount = symmetryBtnCount.toString().indexOf('.') == -1 ? symmetryBtnCount : symmetryBtnCount + 0.5;
  350. frontBtnNum = frontBtnNum.toString().indexOf('.') == -1 ? frontBtnNum : frontBtnNum + 0.5;
  351. behindBtnNum = behindBtnNum.toString().indexOf('.') == -1 ? behindBtnNum : behindBtnNum + 0.5;
  352. if (pageNumber < frontBtnNum) {
  353. if (options.showFirstLastBtn) {
  354. html = this.renderGroupPages(1, pageBtnCount - 2, pageNumber);
  355. html.push(nextPage);
  356. html.push(lastPage);
  357. } else {
  358. html = this.renderGroupPages(1, pageBtnCount - 1, pageNumber);
  359. html.push(nextPage);
  360. }
  361. }
  362. else if (pageNumber > behindBtnNum) {
  363. if (options.showFirstLastBtn) {
  364. html = this.renderGroupPages(lastPageNumber - pageBtnCount + 3, pageBtnCount - 2, pageNumber);
  365. html.unshift(prevPage);
  366. html.unshift(firstPage);
  367. } else {
  368. html = this.renderGroupPages(lastPageNumber - pageBtnCount + 2, pageBtnCount - 1, pageNumber);
  369. html.unshift(prevPage);
  370. }
  371. }
  372. else {
  373. if (options.showFirstLastBtn) {
  374. html = this.renderGroupPages(pageNumber - symmetryBtnCount, pageBtnCount - 4, pageNumber);
  375. html.unshift(prevPage);
  376. html.push(nextPage);
  377. html.unshift(firstPage);
  378. html.push(lastPage);
  379. } else {
  380. html = this.renderGroupPages(pageNumber - symmetryBtnCount, pageBtnCount - 2, pageNumber);
  381. html.unshift(prevPage);
  382. html.push(nextPage);
  383. }
  384. }
  385. }
  386. return html;
  387. },
  388. renderGroupPages: function (beginPageNum, count, currentPage) {
  389. var html = [];
  390. for (var i = 0; i < count; i++) {
  391. var page = this.renderPerPage(beginPageNum, beginPageNum - 1);
  392. if (beginPageNum === currentPage)
  393. page.addClass("active");
  394. html.push(page);
  395. beginPageNum++;
  396. }
  397. return html;
  398. },
  399. renderPerPage: function (text, value) {
  400. return $("<li><a data-page-index='" + value + "'>" + text + "</a></li>");
  401. },
  402. renderInfo: function (currentPageIndex, currentPageSize, total, infoFormat, noInfoText) {
  403. if (total <= 0) {
  404. return noInfoText;
  405. } else {
  406. var startNum = (currentPageIndex * currentPageSize) + 1;
  407. var endNum = (currentPageIndex + 1) * currentPageSize;
  408. endNum = endNum >= total ? total : endNum;
  409. return infoFormat.replace('{start}', startNum).replace('{end}', endNum).replace('{total}', total);
  410. }
  411. },
  412. //计算最大分页数
  413. calLastPageNum: function (total, pageSize) {
  414. total = utility.convertInt(total);
  415. pageSize = utility.convertInt(pageSize);
  416. var i = total / pageSize;
  417. return utility.isDecimal(i) ? parseInt(i) + 1 : i;
  418. }
  419. };
  420. pagination.check = {
  421. //校验跳转页数有效性
  422. checkJumpPage: function (pageIndex) {
  423. var reg = /^\+?[1-9][0-9]*$/;
  424. return reg.test(pageIndex);
  425. }
  426. };
  427. var utility = {
  428. //转换为int
  429. convertInt: function (i) {
  430. if (typeof i === 'number') {
  431. return i;
  432. } else {
  433. var j = parseInt(i);
  434. if (!isNaN(j)) {
  435. return j;
  436. } else {
  437. throw new Error("convertInt Type Error. Type is " + typeof i + ', value = ' + i);
  438. }
  439. }
  440. },
  441. //返回是否小数
  442. isDecimal: function (i) {
  443. return parseInt(i) !== i;
  444. },
  445. //匹配对象名称(递归)
  446. mapObjectNameRecursion: function (object, name) {
  447. var obj = object;
  448. var arr = name.split('.');
  449. for (var i = 0; i < arr.length; i++) {
  450. obj = utility.mapObjectName(obj, arr[i]);
  451. }
  452. return obj;
  453. },
  454. //匹配对象名称
  455. mapObjectName: function (object, name) {
  456. var value = null;
  457. for (var i in object) {
  458. //过滤原型属性
  459. if (object.hasOwnProperty(i)) {
  460. if (i == name) {
  461. value = object[i];
  462. break;
  463. }
  464. }
  465. }
  466. return value;
  467. },
  468. deserializeParams: function (params) {
  469. var newParams = {};
  470. if (typeof params === 'string') {
  471. var arr = params.split('&');
  472. for (var i = 0; i < arr.length; i++) {
  473. var a = arr[i].split('=');
  474. newParams[a[0]] = decodeURIComponent(a[1]);
  475. }
  476. }
  477. else if (params instanceof Array) {
  478. for (var i = 0; i < params.length; i++) {
  479. newParams[params[i].name] = decodeURIComponent(params[i].value);
  480. }
  481. }
  482. else if (typeof params === 'object') {
  483. newParams = params;
  484. }
  485. return newParams;
  486. }
  487. }
  488. $.fn.pagination = function (option) {
  489. if (typeof option === 'undefined') {
  490. return $(this).data('pagination') || false;
  491. } else {
  492. var result;
  493. var args = arguments;
  494. this.each(function () {
  495. var $this = $(this);
  496. var data = $this.data('pagination');
  497. if (!data && typeof option === 'string') {
  498. throw new Error('MricodePagination is uninitialized.');
  499. }
  500. else if (data && typeof option === 'object') {
  501. throw new Error('MricodePagination is initialized.');
  502. }
  503. //初始化
  504. else if (!data && typeof option === 'object') {
  505. var options = typeof option == 'object' && option;
  506. var data_api_options = $this.data();
  507. options = $.extend(options, data_api_options);
  508. $this.data('pagination', (data = new Page(this, options)));
  509. }
  510. else if (data && typeof option === 'string') {
  511. result = data[option].apply(data, Array.prototype.slice.call(args, 1));
  512. }
  513. });
  514. return typeof result === 'undefined' ? this : result;
  515. }
  516. }
  517. });