jquery【插件】 pagination使用

果学网 -专注IT在线www.prismcollege.com

原文:http://zccst.iteye.com/blog/1415848,http://blog.youkuaiyun.com/luoyeyu1989/article/details/7000865

http://my.oschina.net/alexgaoyh/blog/225397

先分享一个jquery分页插件演示大全,很强大啊。http://tool.oschina.net/jquery

1,下载3个文件 
分别为:jquery-1.7.1.js、jquery.pagination.js、pagination.css 

2,准备好服务器端返回结果 
主要代码如下: 
Php代码   收藏代码
  1. $members = array(array().......);  //详见附件  
  2. $total          = count($members);  
  3. $pageIndex      = $_POST['pageIndex'];  
  4. $items_per_page = $_POST['items_per_page'];  
  5.   
  6. $result = array();  
  7. $start = $pageIndex * $items_per_page;  
  8. $end   = ($pageIndex+1) * $items_per_page;  
  9. if($end > $total){$end = $total;}  
  10. for($i = $start$i < $end$i++){  
  11.     $result[] = $members[$i];  
  12. }  
  13.   
  14. print json_encode(array('total'=>$total,'result'=>$result));  


3,前端js代码(核心) 
Js代码   收藏代码
  1. var items_per_page = 3;  
  2. var page_index = 0;  
  3.   
  4. function getDataList(index){  
  5.     var pageIndex = index;  
  6.     $.ajax({  
  7.         type: "POST",  
  8.         url: "members.php",  
  9.         data: "pageIndex="+pageIndex+'&items_per_page='+items_per_page,  
  10.         dataType: 'json',  
  11.         contentType: "application/x-www-form-urlencoded",  
  12.         success: function(msg){  
  13.             var total = msg.total;  
  14.             var html = '<table><tr><th>姓名</th><th>工作时间</th><th>籍贯</th><th>职务</th><th>生卒年</th><th>操作</th></tr>';  
  15.             $.each(msg.result,function(i,n){      
  16.                 html += '<tr><td>'+n[0]+'</td><td>'+n[1]+'</td><td>'+n[2]+'</td><td>'+n[3]+'</td><td>'+n[4]+'</td>'  
  17.                 html += '<td><a href=#>删除</a></td></tr>';  
  18.             });  
  19.             html += '</table>';  
  20.             $('#Searchresult').html(html);  
  21.               
  22.             //分页-只初始化一次  
  23.             if($("#Pagination").html().length == ''){  
  24.                 $("#Pagination").pagination(total, {  
  25.                     'items_per_page'      : items_per_page,  
  26.                     'num_display_entries' : 10,  
  27.                     'num_edge_entries'    : 2,  
  28.                     'prev_text'           : "上一页",  
  29.                     'next_text'           : "下一页",  
  30.                     'callback'            : pageselectCallback  
  31.                 });  
  32.             }  
  33.         }  
  34.     });  
  35. }  
  36.   
  37.   
  38. function pageselectCallback(page_index, jq){  
  39.     getDataList(page_index);  
  40. }  
  41.   
  42. $(document).ready(function(){  
  43.     getDataList(page_index);  
  44. });  


4,前端html 
Html代码   收藏代码
  1. <dl id="Searchresult">  
  2.     <dt>Search Results will be inserted here ...</dt>  
  3. </dl>  
  4. <br style="clear:both;" />  
  5. <div id="Pagination" class="pagination"></div>  
  6. <br style="clear:both;" />  

批注: 
(1)jquery.js和jquery.pagination.js插件的加载有先后顺序,不能颠倒。特别是在复杂的页面中。 
(2)jquery.pagination.js实现可以有很多种。不同的分页插件,使用时可能会有差别,所以最好有足够的js功底,读懂那些插件是如何实现,以及如何引用。 
(3)pagination.css是样式,可以独立出来。也即可以使用很多种不同的样式修饰,不必是给出的那一个。 

当然这样的话数据会重复加载2次

--第一次
$(document).ready(function(){  
    getDataList(page_index);  
});  
---第二次
'callback': pageselectCallback  

暂时解决方法是:

第一次加载且求出数据和分页大小,分页count等,等callback的时候判断一个DOM或input的状态,然后修改即可,
如:
$(document).ready(function() {
        $.ajax({
            type: "get",
            data: "page='' &S=" + S + "&domain=" + domain + "&pagesize="+dopagesize,
            url: "<?php echo $cmsapi; ?>/news",
            dataType: "jsonp",
            jsonp: "callback",
            jsonpCallback: "jsonpNewsList",
            success: function(data) {
                if (data.result == 200) {
                    $('#aresult').empty();
                    if (!$.isEmptyObject(data.data.list)) {

                        $.each(data.data.list, function(a, list) { //装载对应分页的内容 
                            $("#aresult").append('<li><span><a href=" detail-' + list.id + '.html"><div>' + list.title + '</div></a></span></li>');
                        });
                    } else {
                        $("#aresult").append('<li><span class="s_check">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;暂无数据</span></li>');
                    }
                }
                /**
                 * 初始化完成 显示分页   
                 */
                initPagination(data.data.pages.itemCount, dopagesize);   

            },
            error: function() {
                alert('参数错误');
            }
        });
    });

function initPagination(count, pagesize) {

        // 创建分页
        $("#Pagination").pagination(count, {//共24条
            num_edge_entries: 1, //边缘页数 隐藏之前或之后个数
            num_display_entries: 4, //主体页数显示8个多出隐藏
            callback: pageselectCallback,
            items_per_page: pagesize, //每页显示的3条目数   $this->pagesize
            prev_text: "前一页",
            next_text: "后一页"
        });
    }

  function pageselectCallback(page_index, jq) {   //page_index 前一个表示您当前点击的那个分页的页数索引值
        /**
         * 扩展: 查询客户的关键字搜索
         */
        var search_type = $("#search_type").val();
        var orderby = $("#orderby").val();
        var keywords = '';
        var search = {};
        var online_ajax = $("#online_ajax").val();

        if (online_ajax != 1) {
            $.ajax({
                type: "get",
                data: "page=" + (page_index + 1) + " &S=" + S + "&domain=" + domain + "&pagesize=3",
                url: "<?php echo $cmsapi; ?>/news",
                dataType: "jsonp",
                jsonp: "callback",
                jsonpCallback: "jsonpNewsList",
                success: function(data) {
                    if (data.result == 200) {
                        $('#aresult').empty();
                        if (!$.isEmptyObject(data.data.list)) {

                            $.each(data.data.list, function(a, list) { //装载对应分页的内容 
                                $("#aresult").append('<li><span><a href=" detail-' + list.id + '.html"><div>' + list.title + '</div></a></span></li>');
                            });
                        } else {
                            $("#aresult").append('<li><span class="s_check">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;暂无数据</span></li>');
                        }
                    }
                },
                error: function() {
                    alert('参数错误');
                }
            });
        } else { 
            $("#online_ajax").val('2');
        }

        return false;
    }



*********************************************************************************************************************

可以参考下如下改进:

说明
-----------
当您有很多很多数据,需要在网页中以分页的形式显示出来时,这个插件将会帮您创建分页。

使用说明
-----
在页面中引用jQuery和本分页的js及对应的css文件. 
在body中创建一对容纳分页链接的标签。
给这个标签加上一个id或class属性(如: "News-Pagination").
这个属性将被用于jQuery选择器。

接下来,写一个含有new_page_index和paging_container这两个参数的js方法。这个方法是在你单击分页链接后的回调函数。
当你单击页码时,对应的页码会被选中。
    function handlePaginationClick(new_page_index, pagination_container) {
        // 这将选择20个内容数组中的元素
        for(var i=new_page_id;i<;i++) {
            $('#MyContentArea').append(content[i]);
        }
        return false;
    }

这个回调函数中需要用到jQuery对dom操作的相关知识。
里面的代码就可以自己去写。
    
在页面初始化中,当你知道有很多记录要显示出来时,创建如下的分页元素:
    // 第一个参数: 记录总数
    // 第二个参数: 对象options
    $("#News-Pagination").pagination(122, {
        items_per_page:20, //pageSize每页最多显示多少条
        callback:handlePaginationClick
    });

这将在容器中创建分页的导航链接。您会看到
数字1-7,第一个数字是高亮显示的。当您单击另一个页码数字时,
高亮将会改变并且回调函数“handlePaginationClick”
被调用。

通过option和一些元素可以高度配置本插件。

可用的Options:
-----------------
以下为options的具体描述:

callback
    当用户单击页码时,回调函数被调用.这个函数接收到两个参数: 新的页码index和分页容器(dom).
    如果回调函数返回false,则事件不执行. 
    分页中这个回调函数是必不可少的!
    它应该包括你所补充的一些代码。
    为了加快用户体验,你不应该在此通过AJAX来加载内容。相反,您可以预加载一些内容然后通过此函数来分页浏览。
        默认值: "function(){return false;}".

current_page
    分页初始化时,被选中的那一页. 也就是当前页
    默认值: 0
    
items_per_page
    pageSize,每页最多显示的记录数。
    默认值: 10
    
link_to
    分页上的链接. 通常分页是通过onclick事件来触发的. 如果这个链接包含id之类的参数等
    , 它将会替换掉原始的分页链接. 
    默认值: "#"
    
num_display_entries
    可见的页码数量. 建议设置为奇数(对称好看些)
    默认值: 11
    
next_text
    “下一页”的文字
    默认值: "Next"
    
next_show_always
    是否总是显示“下一页”。
    默认值: `true`
    
prev_text
    “上一页”的文字。
    默认值: "Previous"
    
prev_show_always
    是否总是显示“上一页”。
    默认值: true
    
num_edge_entries
    如果设置为1,则显示“首页”与“尾页”。你也可以把它设置大点的数,以便显示更多的链接。
    默认值: 0
    
ellipse_text
    当页码数之间的数字相差很远时,比如:1 2 3 ... 10 11 12
    显示的字符(在span中)
    默认值: "..."

load_first_page
    如果为true则当插件初始化时回调函数被执行。如果你通过ajax来显示内容,那么在初始化分页插件时应把它设置为false;
    默认值: true


自定义事件触发分页
----------------------------------------
    // 跳到第5页 
    $("#News-Pagination").trigger('setPage', [4]);
    // 下一页
    $("#News-Pagination").trigger('nextPage');
    // 上一页
    $("#News-Pagination").trigger('prevPage');

    注:如果指定的页码在页码的范围之内则触发分页事件,否则不触发。

 

 

下载地址:http://ishare.iask.sina.com.cn/f/21330704.html

说明下:

1:ie6下面CSS问题,由于IE6不支持多项选择类(如:".current .next"中间没有空格),导致样式不对。把pagination.css的最后一个样式去掉。

.pagination {
            font-size: 80%;
        }
        
.pagination a {
    text-decoration: none;
    border: solid 1px #AAE;
    color: #15B;
}

.pagination a, .pagination span {
    display: block;
    float: left;
    padding: 0.3em 0.5em;
    margin-right: 5px;
    margin-bottom: 5px;
    min-width:1em;
    text-align:center;
}

.pagination .current {
    background: #eee;
    color: #555;
    border: solid 1px #AAE;
}

2:手动设置"link_to"属性(让页面的url地址像样,xxxxxx.html?id=123):

[javascript]  view plain copy
  1.      <script type="text/javascript">  
  2.        
  3.          // This is a very simple demo that shows how a range of elements can  
  4.          // be paginated.  
  5.          // The elements that will be displayed are in a hidden DIV and are  
  6.          // cloned for display. The elements are static, there are no Ajax   
  7.          // calls involved.  
  8.        
  9.          /** 
  10.           * Callback function that displays the content. 
  11.           * 
  12.           * Gets called every time the user clicks on a pagination link. 
  13.           * 
  14.           * @param {int} page_index New Page index 
  15.           * @param {jQuery} jq the container with the pagination links as a jQuery object 
  16.           */  
  17.          function pageselectCallback(page_index, jq){  
  18.              var new_content = jQuery('#hiddenresult div.result:eq('+page_index+')').clone();  
  19.              $('#Searchresult').empty().append(new_content);  
  20.              //return false;  
  21.          }  
  22.           
  23.          /**  
  24.           * Initialisation function for pagination 
  25.           */  
  26.          function initPagination() {  
  27.              // count entries inside the hidden content  
  28.              var num_entries = jQuery('#hiddenresult div.result').length;  
  29.              // Create content inside pagination element  
  30.              $("#Pagination").pagination(num_entries, {  
  31.                  callback: pageselectCallback,  
  32.                  items_per_page:3,// Show only one item per page  
  33.         num_edge_entries:2,  
  34.         link_to:"?id=__id__"//分页的js中会自动把"__id__"替换为当前的数。0为第一页  
  35.     });  
  36.     //页面加载时选中指定页  
  37.     $("#Pagination").trigger('setPage', [parseInt(getQueryString("id"))]);  
  38.           }  
  39.            
  40.          // When document is ready, initialize pagination  
  41.          $(document).ready(function(){        
  42.              initPagination();  
  43.          });  
  44. //获取url参数  
  45.          function getQueryString(name) {  
  46.     var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)""i");  
  47.     var r = window.location.search.substr(1).match(reg);  
  48.     if (r != nullreturn unescape(r[2]); return null;  
  49. }  
  50.      </script>  

3:ajax就很简单了。不说了。


 jquery.pagination.js 新增 首页 尾页 功能


  在使用 jquery.pagination.js 的时候,发现现有的jquery.pagination.js文件并不包含 首页 尾页 的功能,只有 上一页 下一页 的功能,故修改了第三方的 jquery.pagination.js 的文件,使他可以实现 首页 尾页 的功能,以下为修改后的文件,并加上update的注释

废话不多说,直接上修改后的代码,修改部分已经用 update 注释包含

17-20行

99-103行

141-145行

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
  * This jQuery plugin displays pagination links inside the selected elements.
  *
  * @author Gabriel Birke (birke *at* d-scribe *dot* de)
  * @version 1.2
  * @param {int} maxentries Number of entries to paginate
  * @param {Object} opts Several options (see README for documentation)
  * @return {Object} jQuery Object
  */
jQuery.fn.pagination = function (maxentries, opts){
     opts = jQuery.extend({
         items_per_page:10,
         num_display_entries:10,
         current_page:0,
         num_edge_entries:0,
         link_to: "#" ,
         //update firstPage、lastPage
         first_text: "首页" ,
         last_text: "尾页" ,
         //update
         prev_text: "Prev" ,
         next_text: "Next" ,
         ellipse_text: "..." ,
         prev_show_always: true ,
         next_show_always: true ,
         callback: function (){ return false ;}
     },opts||{});
     
     return this .each( function () {
         /**
          * Calculate the maximum number of pages
          */
         function numPages() {
             return Math.ceil(maxentries/opts.items_per_page);
         }
         
         /**
          * Calculate start and end point of pagination links depending on
          * current_page and num_display_entries.
          * @return {Array}
          */
         function getInterval()  {
             var ne_half = Math.ceil(opts.num_display_entries/2);
             var np = numPages();
             var upper_limit = np-opts.num_display_entries;
             var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0;
             var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(opts.num_display_entries, np);
             return [start,end];
         }
         
         /**
          * This is the event handling function for the pagination links.
          * @param {int} page_id The new page number
          */
         function pageSelected(page_id, evt){
             current_page = page_id;
             drawLinks();
             var continuePropagation = opts.callback(page_id, panel);
             if (!continuePropagation) {
                 if (evt.stopPropagation) {
                     evt.stopPropagation();
                 }
                 else {
                     evt.cancelBubble = true ;
                 }
             }
             return continuePropagation;
         }
         
         /**
          * This function inserts the pagination links into the container element
          */
         function drawLinks() {
             panel.empty();
             var interval = getInterval();
             var np = numPages();
             // This helper function returns a handler function that calls pageSelected with the right page_id
             var getClickHandler = function (page_id) {
                 return function (evt){ return pageSelected(page_id,evt); }
             }
             // Helper function for generating a single link (or a span tag if it's the current page)
             var appendItem = function (page_id, appendopts){
                 page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value
                 appendopts = jQuery.extend({text:page_id+1, classes: "" }, appendopts||{});
                 if (page_id == current_page){
                     var lnk = jQuery( "<span class='current'>" +(appendopts.text)+ "</span>" );
                 }
                 else
                 {
                     var lnk = jQuery( "<a>" +(appendopts.text)+ "</a>" )
                         .bind( "click" , getClickHandler(page_id))
                         .attr('href', opts.link_to.replace(/__id__/,page_id));
                         
                         
                 }
                 if (appendopts.classes){lnk.addClass(appendopts.classes);}
                 panel.append(lnk);
             }
             // update firstPage
             if (opts.first_text && (current_page > 0 || opts.prev_show_always)) {     
                 appendItem(0, { text: opts.first_text, classes: "prev disabled" });          
             }
             // update
             // Generate "Previous"-Link
             if (opts.prev_text && (current_page > 0 || opts.prev_show_always)){
                 appendItem(current_page-1,{text:opts.prev_text, classes: "prev" });
             }
             // Generate starting points
             if (interval[0] > 0 && opts.num_edge_entries > 0)
             {
                 var end = Math.min(opts.num_edge_entries, interval[0]);
                 for ( var i=0; i<end; i++) {
                     appendItem(i);
                 }
                 if (opts.num_edge_entries < interval[0] && opts.ellipse_text)
                 {
                     jQuery( "<span>" +opts.ellipse_text+ "</span>" ).appendTo(panel);
                 }
             }
             // Generate interval links
             for ( var i=interval[0]; i<interval[1]; i++) {
                 appendItem(i);
             }
             // Generate ending points
             if (interval[1] < np && opts.num_edge_entries > 0)
             {
                 if (np-opts.num_edge_entries > interval[1]&& opts.ellipse_text)
                 {
                     jQuery( "<span>" +opts.ellipse_text+ "</span>" ).appendTo(panel);
                 }
                 var begin = Math.max(np-opts.num_edge_entries, interval[1]);
                 for ( var i=begin; i<np; i++) {
                     appendItem(i);
                 }
                 
             }
             // Generate "Next"-Link
             if (opts.next_text && (current_page < np-1 || opts.next_show_always)){
                 appendItem(current_page+1,{text:opts.next_text, classes: "next" });
             }
             // update lastPage
             if (opts.last_text && (current_page < np - 1 || opts.next_show_always)) {           
                  appendItem(np, { text: opts.last_text, classes: "prev disabled" });         
             }
             // update
         }
         
         // Extract current_page from options
         var current_page = opts.current_page;
         // Create a sane value for maxentries and items_per_page
         maxentries = (!maxentries || maxentries < 0)?1:maxentries;
         opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;
         // Store DOM element for easy access from all inner functions
         var panel = jQuery( this );
         // Attach control functions to the DOM element
         this .selectPage = function (page_id){ pageSelected(page_id);}
         this .prevPage = function (){
             if (current_page > 0) {
                 pageSelected(current_page - 1);
                 return true ;
             }
             else {
                 return false ;
             }
         }
         this .nextPage = function (){
             if (current_page < numPages()-1) {
                 pageSelected(current_page+1);
                 return true ;
             }
             else {
                 return false ;
             }
         }
         // When all initialisation is done, draw the links
         drawLinks();
         // call callback function
         //opts.callback(current_page, this);
     });
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值