前端Jquery分页插件jqPaginator

jquery 同时被 2 个专栏收录
3 篇文章 0 订阅
5 篇文章 0 订阅

JQ插件:jqPaginator官网http://jqpaginator.keenwon.com/
环境:Jquery、Bootstrap、使用Ajax动态渲染数据、后端使用MyBatis的PageHelpler分页插件

页面示例
在这里插入图片描述

Html片段

<!-- 头部引入js和样式文件。可在文章最后下载这两个文件 -->
<head>
	<link href="/js/plugins/pagination/jp-paginator.css" rel="stylesheet"/>
	<script src="/js/plugins/pagination/jq-paginator.js"></script>
</head>

...

<!--分页容器,class样式均设置在jp-paginator.css文件中,可根据需要进行更改-->
<div class="customBootstrap">
	<div id="pageBox" class="pagination"></div>
	<div class="pageBoxInfo">总计xx 条,共xx 页</div>
</div>

...

js代码

$(document).ready(function () {
	//初始化分页插件
    $('#pageBox').jqPaginator({
        totalPages: 11,   //总页数。这里可以随便设置大于0的数,后面会动态更改
        visiblePages: 10, //显示页码按钮个数
        currentPage: 1,   //当前页
        first: '<li class="first"><a href="javascript:void(0);">首页<\/a><\/li>',
        prev: '<li class="prev"><a href="javascript:void(0);"><i class="arrow arrow2"></i>上一页<\/a><\/li>',
        next: '<li class="next"><a href="javascript:void(0);">下一页<i class="arrow arrow3"></i><\/a><\/li>',
        last: '<li class="last"><a href="javascript:void(0);">尾页<\/a><\/li>',
        page: '<li class="page"><a href="javascript:void(0);">{{page}}<\/a><\/li>',
        onPageChange: function (num, type) {
        	//onPageChange触发条件:初始化分页插件时、改变页码时
            //console.log('当前第' + num + '页');
            loading(num, 10);
        }
    });
		
	 /**
     * 异步加载数据,可在任意方法调用该函数,进行分页查询,也可传入额外的查询条件
     * @param pageNum 第几页
     * @param pageSize 每页显示的数量
     */
	function loading(pageNum = 1, pageSize = 10) {
        $.ajax({
            type: 'GET',
            url: "/xxx/xxx",
            data: {pageNum, pageSize},
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
					//后台返回数据
					let list = data.result.list;		//数据列表
					let pageNum = data.result.pageNum;	//当前页码
					let pages = data.result.pages; 		//总页码
					let total = data.result.total;		//总数
				
                	//使用jq操作dom,渲染数据到页面,这里根据自己的需求去渲染
                    let root = $('#table');
                    root.empty();
					root.append(htmlTab1(list));
                    
                    //设置分页信息,从后台返回的数据获取当前页码和总页码
                    $('#pageBox').jqPaginator('option', {
                        currentPage: pageNum ,
                        totalPages: pages ? pages : 1
                    });
                    //显示汇总信息
                    $('#pageBox').next().html("总计" + total  + " 条,共" + pages + " 页")
                }
            },
        });
    };
}

以上配置完成。


相关文件下载,直接复制保存为文件
jp-paginator.css


/*#fb9400 */
.customBootstrap{
    overflow: hidden;
}
.customBootstrap .pagination>li>a{margin-right:5px;border-radius:2px;background:#fff;color:#333;border-color:#ccc;padding:6px 15px}
.customBootstrap .pagination>li>a:hover,.customBootstrap .pagination>li>a:focus{color:#fff;background:#00B0E5;border-color:#00B0E5}
.customBootstrap .pagination>.active>a,.customBootstrap .pagination>.active>a:hover,.customBootstrap .pagination>.active>a:focus{color:#fff;background:#00B0E5;border-color:#00B0E5}
.customBootstrap .pagination {
    float:left;
    margin: 10px 0;
}
.customBootstrap .pageBoxInfo{
    float: left;
    height: 52px;
    line-height: 48px;
}
.customBootstrap .arrow{
    display: inline-block;
    overflow: hidden;
    vertical-align: middle;
    float: none;
}
.customBootstrap .arrow2{
    border-left: 5px dashed transparent;
    border-bottom: 5px dashed transparent;
    border-top: 5px dashed transparent;
    border-right: 5px solid #ccc;
}
.customBootstrap .arrow3{
    border-top: 5px dashed transparent;
    border-bottom: 5px dashed transparent;
    border-right: 5px dashed transparent;
    border-left: 5px solid #ccc;
}
.customBootstrap .pagination .arrow2{margin:0px 8px 3px 0px}
.customBootstrap .pagination a:hover .arrow2{border-right-color:#fff}
.customBootstrap .pagination .arrow3{margin:0px 0px 3px 8px}
.customBootstrap .pagination a:hover .arrow3{border-left-color:#fff}

jq-paginator.js

/*!
 * jq-paginator v2.0.2
 * http://jqPaginator.keenwon.com
 */

(function () {
  'use strict';

  /* eslint-env jquery */

  var $ = jQuery;

  $.jqPaginator = function (el, options) {
    if (!(this instanceof $.jqPaginator)) {
      return new $.jqPaginator(el, options)
    }

    var self = this;

    self.$container = $(el);

    self.$container.data('jqPaginator', self);

    self.init = function () {
      if (options.first || options.prev || options.next || options.last || options.page) {
        options = $.extend(
          {},
          {
            first: '',
            prev: '',
            next: '',
            last: '',
            page: ''
          },
          options
        );
      }

      self.options = $.extend({}, $.jqPaginator.defaultOptions, options);

      self.verify();

      self.extendJquery();

      self.render();

      self.fireEvent(this.options.currentPage, 'init');
    };

    self.verify = function () {
      var opts = self.options;

      if (!self.isNumber(opts.totalPages)) {
        throw new Error('[jqPaginator] type error: totalPages')
      }

      if (!self.isNumber(opts.totalCounts)) {
        throw new Error('[jqPaginator] type error: totalCounts')
      }

      if (!self.isNumber(opts.pageSize)) {
        throw new Error('[jqPaginator] type error: pageSize')
      }

      if (!self.isNumber(opts.currentPage)) {
        throw new Error('[jqPaginator] type error: currentPage')
      }

      if (!self.isNumber(opts.visiblePages)) {
        throw new Error('[jqPaginator] type error: visiblePages')
      }

      if (!opts.totalPages && !opts.totalCounts) {
        throw new Error('[jqPaginator] totalCounts or totalPages is required')
      }

      if (!opts.totalPages && opts.totalCounts && !opts.pageSize) {
        throw new Error('[jqPaginator] pageSize is required')
      }

      if (opts.totalCounts && opts.pageSize) {
        opts.totalPages = Math.ceil(opts.totalCounts / opts.pageSize);
      }

      if (opts.currentPage < 1 || opts.currentPage > opts.totalPages) {
        throw new Error('[jqPaginator] currentPage is incorrect')
      }

      if (opts.totalPages < 1) {
        throw new Error('[jqPaginator] totalPages cannot be less currentPage')
      }
    };

    self.extendJquery = function () {
      $.fn.jqPaginatorHTML = function (s) {
        return s
          ? this.before(s).remove()
          : $('<p>')
            .append(this.eq(0).clone())
            .html()
      };
    };

    self.render = function () {
      self.renderHtml();
      self.setStatus();
      self.bindEvents();
    };

    self.renderHtml = function () {
      var html = [];

      var pages = self.getPages();
      for (var i = 0, j = pages.length; i < j; i++) {
        html.push(self.buildItem('page', pages[i]));
      }

      self.isEnable('prev') && html.unshift(self.buildItem('prev', self.options.currentPage - 1));
      self.isEnable('first') && html.unshift(self.buildItem('first', 1));
      self.isEnable('statistics') && html.unshift(self.buildItem('statistics'));
      self.isEnable('next') && html.push(self.buildItem('next', self.options.currentPage + 1));
      self.isEnable('last') && html.push(self.buildItem('last', self.options.totalPages));

      if (self.options.wrapper) {
        self.$container.html(
          $(self.options.wrapper)
            .html(html.join(''))
            .jqPaginatorHTML()
        );
      } else {
        self.$container.html(html.join(''));
      }
    };

    self.buildItem = function (type, pageData) {
      var html = self.options[type]
        .replace(/{{page}}/g, pageData)
        .replace(/{{totalPages}}/g, self.options.totalPages)
        .replace(/{{totalCounts}}/g, self.options.totalCounts);

      return $(html)
        .attr({
          'jp-role': type,
          'jp-data': pageData
        })
        .jqPaginatorHTML()
    };

    self.setStatus = function () {
      var options = self.options;

      if (!self.isEnable('first') || options.currentPage === 1) {
        $('[jp-role=first]', self.$container).addClass(options.disableClass);
      }
      if (!self.isEnable('prev') || options.currentPage === 1) {
        $('[jp-role=prev]', self.$container).addClass(options.disableClass);
      }
      if (!self.isEnable('next') || options.currentPage >= options.totalPages) {
        $('[jp-role=next]', self.$container).addClass(options.disableClass);
      }
      if (!self.isEnable('last') || options.currentPage >= options.totalPages) {
        $('[jp-role=last]', self.$container).addClass(options.disableClass);
      }

      $('[jp-role=page]', self.$container).removeClass(options.activeClass);
      $('[jp-role=page][jp-data=' + options.currentPage + ']', self.$container).addClass(options.activeClass);
    };

    self.getPages = function () {
      var pages = [];

      var visiblePages = self.options.visiblePages;

      var currentPage = self.options.currentPage;

      var totalPages = self.options.totalPages;

      if (visiblePages > totalPages) {
        visiblePages = totalPages;
      }

      var half = Math.floor(visiblePages / 2);
      var start = currentPage - half + 1 - (visiblePages % 2);
      var end = currentPage + half;

      if (start < 1) {
        start = 1;
        end = visiblePages;
      }
      if (end > totalPages) {
        end = totalPages;
        start = 1 + totalPages - visiblePages;
      }

      var itPage = start;
      while (itPage <= end) {
        pages.push(itPage);
        itPage++;
      }

      return pages
    };

    self.isNumber = function (value) {
      var type = typeof value;
      return type === 'number' || type === 'undefined'
    };

    self.isEnable = function (type) {
      return self.options[type] && typeof self.options[type] === 'string'
    };

    self.switchPage = function (pageIndex) {
      self.options.currentPage = pageIndex;
      self.render();
    };

    self.fireEvent = function (pageIndex, type) {
      return typeof self.options.onPageChange !== 'function' || self.options.onPageChange(pageIndex, type) !== false
    };

    self.callMethod = function (method, options) {
      switch (method) {
        case 'option':
          self.options = $.extend({}, self.options, options);
          self.verify();
          self.render();
          break;
        case 'destroy':
          self.$container.empty();
          self.$container.removeData('jqPaginator');
          break;
        default:
          throw new Error('[jqPaginator] method "' + method + '" does not exist')
      }

      return self.$container
    };

    self.bindEvents = function () {
      var opts = self.options;

      self.$container.off();
      self.$container.on('click', '[jp-role]', function () {
        var $el = $(this);
        if ($el.hasClass(opts.disableClass) || $el.hasClass(opts.activeClass)) {
          return
        }

        var pageIndex = +$el.attr('jp-data');
        if (self.fireEvent(pageIndex, 'change')) {
          self.switchPage(pageIndex);
        }
      });
    };

    self.init();

    return self.$container
  };

  $.jqPaginator.defaultOptions = {
    wrapper: '',
    first: '<li class="first"><a href="javascript:;">First</a></li>',
    prev: '<li class="prev"><a href="javascript:;">Previous</a></li>',
    next: '<li class="next"><a href="javascript:;">Next</a></li>',
    last: '<li class="last"><a href="javascript:;">Last</a></li>',
    page: '<li class="page"><a href="javascript:;">{{page}}</a></li>',
    totalPages: 0,
    totalCounts: 0,
    pageSize: 0,
    currentPage: 1,
    visiblePages: 7,
    disableClass: 'disabled',
    activeClass: 'active',
    onPageChange: null
  };

  $.fn.jqPaginator = function () {
    var self = this;

    var args = Array.prototype.slice.call(arguments);

    if (typeof args[0] === 'string') {
      var $instance = $(self).data('jqPaginator');
      if (!$instance) {
        throw new Error('[jqPaginator] the element is not instantiated')
      } else {
        return $instance.callMethod(args[0], args[1])
      }
    } else {
      return new $.jqPaginator(this, args[0])
    }
  };

}());

  • 0
    点赞
  • 1
    评论
  • 6
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值