前端jquery分页插件推荐

时间: 作者:admin 浏览:


很久没更新文章了,最近项目需要使用前端来做分页,于是找了一款现有的jquery分页插件进行修改了一下,增加了些新功能以及加大了兼容性,其本质其实就是使用$.ajax()方法进行包装,把修改过后的代码贴出来给大家吧(末尾提供下载)

/*
* Version 1.0
* 2015-12-20 by sullivan
* AJAX Pager
*/

//辅助方法:格式化字符串
window.stringFormat = function() {
    if (arguments.length == 0) return null;
    var str = arguments[0];

    for (var i = 1; i < arguments.length; i++) {
        var reg = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(reg, arguments[i]);
    }

    return str;
}

//辅助方法:parseURL
window.parseURL =  function(url) {
    var a = document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':', ''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function () {
            var ret = {},
            seg = a.search.replace(/^\?/, '').split('&'),
            len = seg.length, i = 0, s;
            for (; i < len; i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
        hash: a.hash.replace('#', ''),
        path: a.pathname.replace(/^([^\/])/, '/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
        segments: a.pathname.replace(/^\//, '').split('/')
    };
};
(function (window, $) {
    var ajaxPagerObj = window.ajaxPagerObj = {
        opts: {
            pageSize: 10,
            preText: "上一页",
            nextText: "下一页",
            firstText: "首页",
            lastText: "尾页",
            shiftingLeft: 3,
            shiftingRight: 3,
            preLeast: 2,
            nextLeast: 2,
            showFirst: true,
            showLast: true,
            url: "",
            type: "POST",
            dataType: "JSON",
            data: {},
            doPage:function(data){
                if(!data.pageIndex || !data.pageSize){
                    //用于页码字段同步,比如:
                    alert("请在doPage方法里将页码与页长字段同步!,例如:\ndata.Page=data.pageIndex;\ndata.PageSize=data.pageSize;");
                    console.log("请在doPage方法里将页码与页长字段同步!,例如:\ndata.Page=data.pageIndex;\ndata.PageSize=data.pageSize;");
                    //data.Page=data.pageIndex;
                    //data.PageSize=data.pageSize;
                }
            },
            beforeSend: function(){},
            success: function(data){},
            complete: function(){},
            error: function() {
                alert("抱歉,请求出错,请重新请求!");
            },
            pageIndex: 1,
            totalCount: 0,
            totalPage: 0
        },
        pagerElement: null,
        commonHtmlText: {
            spanHtml: "<span class='{0}'>{1}</span>",
            pageIndexHtml: "<a href='javascript:void(0)' onclick='ajaxPagerObj.doPage({0},{1},{2})'>{3}</a>",
            rightHtml: "<span class='text'>   共 {0} 页, 到第</span> <input type='text' id='txtToPager' value={1} /><span class='text'>页</span> <button id='btnJump' onclick='ajaxPagerObj.jumpToPage();return false;' >确定</button>",
            clearFloatHtml: "<div style='clear:both;'></div>",
            stringEmpty: ""
        },
        init: function (obj,op) {
            var _self = this;
            _self.opts = $.extend({}, _self.opts, op || {});
            _self.pagerElement = obj;
            _self.doPage(_self.opts.pageIndex, _self.opts.pageSize, _self.opts.data);
            return _self.opts;
        },
        doPage: function (index, pageSize, data) {
            var _self = this;
            var dataJson=$.extend(data || {}, { pageIndex: index,pageSize:pageSize || 10 })

            if(typeof _self.opts.doPage=="function"){
                _self.opts.doPage(dataJson);
            }
            _self.opts.pageIndex=index;
            _self.opts.pageSize=pageSize;
            _self.opts.data=data;

            var returnRequest = $.ajax({
                type: _self.opts.type,
                data:dataJson ,
                dataType: _self.opts.dataType,
                url: _self.opts.url,
                beforeSend: function (xhr) {
                    if(returnRequest){
                        returnRequest.abort();
                    }
                    if(typeof _self.opts.beforeSend=="function"){
                        _self.opts.beforeSend(xhr);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if(typeof _self.opts.error=="function"){
                        _self.opts.error(XMLHttpRequest, textStatus, errorThrown);
                    }
                },
                success: function (data) {
                    if(typeof _self.opts.success=="function"){
                        _self.opts.success(data);
                        //后台返回数据格式:{"total":0,"items":[]}
                        _self.opts.totalCount =_self.getTotalCount(_self.opts) || data.TotalCount || _self.opts.totalCount;
                        _self.getTotalPage();
                        if (_self.opts.totalCount > 0 && _self.opts.pageIndex > 0) {
                            var pageTextArr = new Array;
                            _self.createPreAndFirstBtn(pageTextArr);
                            _self.createIndexBtn(pageTextArr);
                            _self.createNextAndLastBtn(pageTextArr);
                            _self.renderHtml(pageTextArr);
                        }
                    }
                },
                complete: function (data) {
                    if(typeof _self.opts.complete=="function"){
                        _self.opts.complete(data);
                    }
                }
            });
        },
        getTotalPage: function() {
            var _self = this;
            _self.opts.totalPage = Math.ceil(_self.opts.totalCount / _self.opts.pageSize);
        },
        getTotalCount: function(opts) {
            var _self = this;
            return '';
        },
        createPreAndFirstBtn: function (pageTextArr) {
            var _self = this;
            if (_self.opts.pageIndex == 1) {
                if (_self.opts.showFirst) pageTextArr.push(_self.createSpan(_self.opts.firstText, 'disenable'));
                    pageTextArr.push(_self.createSpan(_self.opts.preText, 'disenable'));
                } else {
                    if (_self.opts.showFirst) {
                        pageTextArr.push(_self.createIndexText(1, _self.opts.firstText));
                }
                pageTextArr.push(_self.createIndexText(_self.opts.pageIndex - 1, _self.opts.preText));
            }
        },
        createNextAndLastBtn: function (pageTextArr) {
            var _self = this;
            if (_self.opts.pageIndex == _self.opts.totalPage) {
                pageTextArr.push(_self.createSpan(_self.opts.nextText, 'disenable'));
                if (_self.opts.showLast) pageTextArr.push(_self.createSpan(_self.opts.lastText, 'disenable'));
            } else {
                pageTextArr.push(_self.createIndexText(_self.opts.pageIndex + 1, _self.opts.nextText));
                if (_self.opts.showLast)  pageTextArr.push(_self.createIndexText(_self.opts.totalPage, _self.opts.lastText));
            }
        },
        createIndexBtn: function (pageTextArr) {
            /*
            前:当前页 > 偏移量 + 至少保留 + 1
            后:当前页 < 总页码 - 偏移量 - 至少保留
            */
            var _self = this;
            var shiftingLeftStart = _self.opts.shiftingLeft + _self.opts.preLeast + 1;
            var shiftingRightStart = _self.opts.totalPage - _self.opts.shiftingRight - _self.opts.nextLeast - 1;
            /*页码*/
            if (_self.opts.pageIndex > shiftingLeftStart) {
                for (i = 1; i <= _self.opts.preLeast; i++) {
                    pageTextArr.push(_self.createIndexText(i, i));
                }
                pageTextArr.push(_self.createSpan('...'));

                for (i = _self.opts.pageIndex - _self.opts.shiftingLeft; i < _self.opts.pageIndex; i++) {
                    pageTextArr.push(_self.createIndexText(i, i));
                }
            } else {
                for (i = 1; i < _self.opts.pageIndex; i++) {
                    pageTextArr.push(_self.createIndexText(i, i));
                }
            }

            pageTextArr.push(_self.createSpan(_self.opts.pageIndex, 'current'));

            if (_self.opts.pageIndex <= shiftingRightStart) {
                for (i = _self.opts.pageIndex + 1; i < _self.opts.pageIndex + 1 + _self.opts.shiftingRight; i++) {
                    pageTextArr.push(_self.createIndexText(i, i));
                }

                pageTextArr.push(_self.createSpan('...'));

                for (i = _self.opts.totalPage - 1; i <= _self.opts.totalPage; i++) {
                    pageTextArr.push(_self.createIndexText(i, i));
                }

            } else {
                for (i = _self.opts.pageIndex + 1; i <= _self.opts.totalPage; i++) {
                    pageTextArr.push(_self.createIndexText(i, i));
                }
            }
        },
        renderHtml: function (pageTextArr) {
            var _self = this;
            var pageText = _self.commonHtmlText.stringEmpty;
            for (var i = 0; i < pageTextArr.length; i++) {
                pageText += pageTextArr[i];
            }
            _self.pagerElement.html(pageText).append(stringFormat(_self.commonHtmlText.rightHtml, _self.opts.totalPage, _self.opts.pageIndex)).append(_self.commonHtmlText.clearFloatHtml);
        },
        createSpan: function (text, className) {
            var _self = this;
            return stringFormat(_self.commonHtmlText.spanHtml, className ? className : _self.commonHtmlText.stringEmpty, text);
        },
        createIndexText: function (index, text) {
            var _self = this;
            return stringFormat(_self.commonHtmlText.pageIndexHtml, index, _self.opts.pageSize, JSON.stringify(_self.opts.data), text);
        },
        jumpToPage: function() {
            var _self = this;
            var $txtToPager = $("#txtToPager", _self.pagerElement);
            var index = parseInt($txtToPager.val());
            if (!isNaN(index) && index > 0 && index <= _self.opts.totalPage) {
                _self.doPage(index, _self.opts.pageSize, _self.opts.data);
            } else {
                $txtToPager.focus();
            }
        }
    }

    $.fn.ajaxPager = function (option) {
        return ajaxPagerObj.init($(this),option);
    };
})(window, jQuery);

参考样式


/**pager**/
.ajaxPager-box {
    display:inline-block;
    padding: 0px 10px;
    text-align:center;
    font-size:0;
}

.ajaxPager-box span {
    display: block;
    float: left;
    padding: 1px 12px;
    margin-right: 4px;
    font-size:12px;
}

.ajaxPager-box span.current {
    background-color: #eb6906;
    color: #FFF;
    border: solid 1px #DDD;
}

.ajaxPager-box span.disenable {
    color: #CECECE;
    background-color: #FFF;
    border: solid 1px #DDD;
}

.ajaxPager-box span.text {
    padding: 1px 8px;
    color: #333;
}

.ajaxPager-box a {
    display: block;
    float: left;
    padding: 1px 12px;
    margin-right: 4px;
    text-decoration: none;
    border: solid 1px #DDD;
    color: #666 !important;
    font-size:12px;
}

.ajaxPager-box a:active,
.ajaxPager-box a:visited,
.ajaxPager-box a:focus,
.ajaxPager-box a:hover{
    border: solid 1px #eb6906;
    color: #eb6906 !important;
}

.ajaxPager-box input[type=text] {
    padding:0;
    border: solid 1px #DDD;
    width: 30px;
    height: 20px;
    line-height: 20px;
    float: left;
    margin-right: 4px;
    margin-bottom:0;
    text-align: center;
    border-radius:0;
    font-size:12px;
    color:#555;
}

.ajaxPager-box button {
    cursor: pointer;
    border: solid 1px #DDD;
    height: 22px;
    line-height: 20px;
    float: left;
    margin:1px 0 0 4px;
    padding: 1px 12px;
    color: #666;
    background-color:#EFEFEF;
    font-size:12px;
}

.ajaxPager-box button:active,
.ajaxPager-box button:visited,
.ajaxPager-box button:focus,
.ajaxPager-box button:hover{
    border: solid 1px #eb6906 !important;
    color: #eb6906 !important;
    outline:none;
}

点击下载以上插件

微信公众号
微信公众号:
  • 前端全栈之路(微信群)
前端QQ交流群
前端QQ交流群:
  • 794324979
  • 734802480(已满)

更多文章

栏目文章


Copyright © 2014-2023 seozhijia.net 版权所有-粤ICP备13087626号-4