Jquery.Pagination分页插件的学习

来源:互联网 发布:如何对待网络语言 编辑:程序博客网 时间:2024/05/13 01:01

http://blog.csdn.net/xiaochengzi_2015/article/details/51762432


编程小白,文章中出现的谬误希望大神指点

工作接到一个任务,需要把现在pagination的样式修改成前端给的样式,当时心慌慌,幸好pagination的源码不太多,参考了一下网上的讲解代码,把学习过程中遇到的问题和对pagination的理解记录下来。

先看最终效果



直接上代码

[javascript] view plain copy
  1. /** 
  2.  * This jQuery plugin displays pagination links inside the selected elements. 
  3.  *  
  4.  * This plugin needs at least jQuery 1.4.2 
  5.  * 
  6.  * @author Gabriel Birke (birke *at* d-scribe *dot* de) 
  7.  * @version 2.2 
  8.  * @param {int} maxentries Number of entries to paginate 
  9.  * @param {Object} opts Several options (see README for documentation) 
  10.  * @return {Object} jQuery Object 
  11.  */  
  12.  (function($){  
  13.     /** 
  14.      * @class Class for calculating pagination values 
  15.      */  
  16.     $.PaginationCalculator = function(maxentries, opts) {  
  17.         this.maxentries = maxentries;  
  18.         this.opts = opts;  
  19.     }  
  20.       
  21.     $.extend($.PaginationCalculator.prototype, {  
  22.         /** 
  23.          * Calculate the maximum number of pages 
  24.          * @method 
  25.          * @returns {Number} 
  26.          */  
  27.         numPages:function() {  
  28.             return Math.ceil(this.maxentries/this.opts.items_per_page);  
  29.         },  
  30.         /** 
  31.          * Calculate start and end point of pagination links depending on  
  32.          * current_page and num_display_entries. 
  33.          * @returns {Array} 
  34.          */  
  35.         getInterval:function(current_page)  {  
  36.             var ne_half = Math.floor(this.opts.num_display_entries/2);  
  37.             var np = this.numPages();  
  38.             var upper_limit = np - this.opts.num_display_entries;  
  39.             var start = current_page > ne_half ? Math.max( Math.min(current_page - ne_half, upper_limit), 0 ) : 0;  
  40.             var end = current_page > ne_half?Math.min(current_page+ne_half + (this.opts.num_display_entries % 2), np):Math.min(this.opts.num_display_entries, np);  
  41.             return {start:start, end:end};  
  42.         }  
  43.     });  
  44.       
  45.     // Initialize jQuery object container for pagination renderers  
  46.     $.PaginationRenderers = {}  
  47.       
  48.     /** 
  49.      * @class Default renderer for rendering pagination links 
  50.      */  
  51.     $.PaginationRenderers.defaultRenderer = function(maxentries, opts) {  
  52.         this.maxentries = maxentries;  
  53.         this.opts = opts;  
  54.         this.pc = new $.PaginationCalculator(maxentries, opts);  
  55.     }  
  56.     $.extend($.PaginationRenderers.defaultRenderer.prototype, {  
  57.         /** 
  58.          * Helper function for generating a single link (or a span tag if it's the current page) 
  59.          * @param {Number} page_id The page id for the new item 
  60.          * @param {Number} current_page  
  61.          * @param {Object} appendopts Options for the new item: text and classes 
  62.          * @returns {jQuery} jQuery object containing the link 
  63.          */  
  64.         createLink:function(page_id, current_page, appendopts){  
  65.             var lnk, np = this.pc.numPages();  
  66.             page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value  
  67.             appendopts = $.extend({text:page_id+1, classes:""}, appendopts||{});  
  68.             if(page_id == current_page){  
  69.                 lnk = $("<a>" + appendopts.text + "</a>");  
  70.             }  
  71.             else  
  72.             {  
  73.                 lnk = $("<a>" + appendopts.text + "</a>")  
  74.                     .attr('href'this.opts.link_to.replace(/__id__/,page_id));  
  75.             }  
  76.             if(appendopts.classes){ lnk.addClass(appendopts.classes); }  
  77.             lnk.data('page_id', page_id);  
  78.             return lnk;  
  79.         },  
  80.         // Generate a range of numeric links   
  81.         appendRange:function(container, current_page, start, end, opts) {  
  82.             var i;  
  83.             for(i=start; i<end; i++) {  
  84.                 this.createLink(i, current_page, opts).appendTo(container);  
  85.             }  
  86.         },  
  87.         getLinks:function(current_page, eventHandler) {  
  88.             var begin, end,  
  89.                 interval = this.pc.getInterval(current_page),  
  90.                 np = this.pc.numPages(),  
  91.                 fragment = $("<div class='wy_1 y_z'></div>");  
  92.               
  93.             //创建首页链接  
  94.             if(this.opts.first_text){  
  95.                 fragment.append(this.createLink(0, 0, {text:this.opts.first_text, classes:"wy_fy"}));  
  96.             }  
  97.   
  98.             // Generate "Previous"-Link  
  99.             if(this.opts.prev_text && (current_page > 0 || this.opts.prev_show_always)){  
  100.                 fragment.append(this.createLink(current_page-1, current_page, {text:this.opts.prev_text, classes:"wy_fy"}));  
  101.             }  
  102.   
  103.   
  104.   
  105.             //创建中间页码显示  
  106.             fragment.append("<span>" + (current_page+1) + "/"+np+"</span>");  
  107.               
  108.             // Generate starting points  
  109.             // if (interval.start > 0 && this.opts.num_edge_entries > 0)  
  110.             // {  
  111.             //  end = Math.min(this.opts.num_edge_entries, interval.start);  
  112.             //  this.appendRange(fragment, current_page, 0, end, {classes:'sp'});  
  113.             //  if(this.opts.num_edge_entries < interval.start && this.opts.ellipse_text)  
  114.             //  {  
  115.             //      jQuery("<span>"+this.opts.ellipse_text+"</span>").appendTo(fragment);  
  116.             //  }  
  117.             // }  
  118.             // // Generate interval links  
  119.             // this.appendRange(fragment, current_page, interval.start, interval.end);  
  120.             // // Generate ending points  
  121.             // if (interval.end < np && this.opts.num_edge_entries > 0)  
  122.             // {  
  123.             //  if(np-this.opts.num_edge_entries > interval.end && this.opts.ellipse_text)  
  124.             //  {  
  125.             //      jQuery("<span>"+this.opts.ellipse_text+"</span>").appendTo(fragment);  
  126.             //  }  
  127.             //  begin = Math.max(np-this.opts.num_edge_entries, interval.end);  
  128.             //  this.appendRange(fragment, current_page, begin, np, {classes:'ep'});  
  129.                   
  130.             // }  
  131.             // Generate "Next"-Link  
  132.             if(this.opts.next_text && (current_page < np-1 || this.opts.next_show_always)){  
  133.                 fragment.append(this.createLink(current_page+1, current_page, {text:this.opts.next_text, classes:"wy_fy"}));  
  134.             }  
  135.   
  136.             //创建尾页链接  
  137.             if(this.opts.end_text){  
  138.                   
  139.                 fragment.append(this.createLink(np-1, np-1, {text:this.opts.end_text, classes:"wy_fy"}));  
  140.             }  
  141.             //创建共多少条  
  142.             fragment.append("<span>共" + this.maxentries + "条</span>");  
  143.             //创建每页多少条  
  144.             fragment.append("<span>每页" + this.opts.items_per_page +"条</span>");  
  145.             //创建跳转  
  146.               
  147.   
  148.             fragment.append("<span>跳转到<input type='text' value='' placeholder='' class='f_input'/>页</span>");  
  149.             if(this.opts.go_text){        
  150.                 fragment.append(this.createLink(current_page, current_page, {text:this.opts.go_text, classes:"go"}));  
  151.             }  
  152.             $('a', fragment).click(eventHandler);  
  153.             return fragment;  
  154.         }  
  155.     });  
  156.       
  157.     // Extend jQuery  
  158.     $.fn.pagination = function(maxentries, opts){  
  159.           
  160.         // Initialize options with default values  
  161.         opts = jQuery.extend({  
  162.             items_per_page:10, //每页最多显示的记录数  
  163.             num_display_entries:11,//可见页码数量  
  164.             current_page:0,//当前页  
  165.             num_edge_entries:1,//如果设置为1,显示首页与尾页,然而并没有什么效果,不知道为什么  
  166.             link_to:"#",//链接  
  167.             prev_text:"Prev",  
  168.             next_text:"Next",  
  169.             ellipse_text:"...",//当页码之间的数组相差很远时,显示的内容  
  170.             prev_show_always:true,  
  171.             next_show_always:true,  
  172.             renderer:"defaultRenderer",  
  173.             load_first_page:false,//插件初始化时被执行  
  174.             callback:function(){return false;}  
  175.         },opts||{});  
  176.           
  177.         var containers = this,  
  178.             renderer, links, current_page;  
  179.           
  180.         /** 
  181.          * This is the event handling function for the pagination links.  
  182.          * @param {int} page_id The new page number 
  183.          */  
  184.         function paginationClickHandler(evt){  
  185.   
  186.               
  187.             var links;  
  188.             var new_current_page = $(evt.target).data('page_id');  
[javascript] view plain copy
  1. <span style="white-space:pre">            </span>//这里就是点击跳转的代码,核心是获取到input框内用户输入的页数,进行简单判断后,将值作为当前页  
[javascript] view plain copy
  1. <span style="white-space:pre">            </span>//传递给selectPage方法,让它重新调用本页方法重新生成链接  
[javascript] view plain copy
  1.     if($(evt.target).attr('class')=='go' && $('input[class=f_input]').val() !='' && !isNaN($('input[class=f_input]').val())){  
  2.         new_current_page = $('input[class=f_input]').val() - 1;  
  3.         new_current_page = Math.min(np-1,Math.max(0,new_current_page));  
  4.     }  
  5.     var continuePropagation = selectPage(new_current_page);  
  6.     if (!continuePropagation) {  
  7.         evt.stopPropagation();  
  8.     }  
  9.     return continuePropagation;  
  10. }  
  11.   
  12. /** 
  13.  * This is a utility function for the internal event handlers.  
  14.  * It sets the new current page on the pagination container objects,  
  15.  * generates a new HTMl fragment for the pagination links and calls 
  16.  * the callback function. 
  17.  */  
  18. function selectPage(new_current_page) {  
  19.     // update the link display of a all containers  
  20.     containers.data('current_page', new_current_page);  
  21.     links = renderer.getLinks(new_current_page, paginationClickHandler);  
  22.     containers.empty();  
  23.     links.appendTo(containers);  
  24.     // call the callback and propagate the event if it does not return false  
  25.     var continuePropagation = opts.callback(new_current_page, containers);  
  26.     return continuePropagation;  
  27. }  
  28.   
  29. // -----------------------------------  
  30. // Initialize containers  
  31. // -----------------------------------  
  32. current_page = opts.current_page;  
  33. containers.data('current_page', current_page);  
  34. // Create a sane value for maxentries and items_per_page  
  35. maxentries = (!maxentries || maxentries < 0)?1:maxentries;  
  36. opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;  
  37.   
  38. if(!$.PaginationRenderers[opts.renderer])  
  39. {  
  40.     throw new ReferenceError("Pagination renderer '" + opts.renderer + "' was not found in jQuery.PaginationRenderers object.");  
  41. }  
  42. renderer = new $.PaginationRenderers[opts.renderer](maxentries, opts);  
  43.   
  44. // Attach control events to the DOM elements  
  45. var pc = new $.PaginationCalculator(maxentries, opts);  
  46. var np = pc.numPages();  
  47. containers.bind('setPage', {numPages:np}, function(evt, page_id) {   
  48.         if(page_id >= 0 && page_id < evt.data.numPages) {  
  49.             selectPage(page_id); return false;  
  50.         }  
  51. });  
[javascript] view plain copy
  1. </pre><pre name="code" class="javascript"><span style="white-space:pre">      </span>这里的PrevPage、nextPage我不知道哪里来的,希望有人讲解,  
  2.         containers.bind('prevPage'function(evt){  
  3.                 var current_page = $(this).data('current_page');  
  4.                 if (current_page > 0) {  
  5.                     selectPage(current_page - 1);  
  6.                 }  
  7.                 return false;  
  8.         });  
  9.         containers.bind('nextPage', {numPages:np}, function(evt){  
  10.                 var current_page = $(this).data('current_page');  
  11.                 if(current_page < evt.data.numPages - 1) {  
  12.                     selectPage(current_page + 1);  
  13.                 }  
  14.                 return false;  
  15.         });  
  16.   
  17.   
  18.         // When all initialisation is done, draw the links  
  19.         links = renderer.getLinks(current_page, paginationClickHandler);  
  20.         containers.empty();  
  21.         links.appendTo(containers);  
  22.         // call callback function  
  23.         if(opts.load_first_page) {  
  24.             opts.callback(current_page, containers);  
  25.         }  
  26.     } // End of $.fn.pagination block  
  27.       
  28. })(jQuery);  

插件首先调用Initialize containers下的方法,构造链接,完成后将生成的内容放到指定ID的容器内,上配置:

[javascript] view plain copy
  1. callback: pageselectCallback,//PageCallback() 为翻页调用次函数。  
  2.            items_per_page:parseInt($("#pages").attr('data-epage')), //每页最多显示的记录数  
  3.            num_display_entries:0,//可见页码数量  
  4.            current_page: parseInt($("#pages").attr('data-page')),  
  5.            num_edge_entries:0,//如果设置为1,显示首页与尾页  
  6.            //link_to:"#",//链接  
  7.            prev_text:"上一页",  
  8.            next_text:"下一页",  
  9.            first_text:"首页",  
  10.            end_text:"尾页",  
  11.            go_text:"GO",  
  12.            ellipse_text:"",//当页码之间的数组相差很远时,显示的内容  
  13.            prev_show_always:true,  
  14.            next_show_always:true,  
  15.            //renderer:"defaultRenderer",  
  16.            load_first_page:false,//插件初始化时被执行  
可以添加自定义参数,比如我添加的first_text、end_text、go_text,这里在构造按钮的时候使用,在这里

[javascript] view plain copy
  1. if(this.opts.first_text){  
  2.                 fragment.append(this.createLink(0, 0, {text:this.opts.first_text, classes:"wy_fy"}));  
  3.             }  

其中的0,0就代表首页,第一个0是页码的起始参数,第二个0是页码的结束参数,那尾页的参数是什么呢? 是Pagination的一个变量np,调用创建链接的函数,其中text就是要显示的内容,first_text就是我们在初始化参数里面自己定义的,classes就是当前连接的样式,可以修改成自己的。
0 0