jQuery Pagination Plugin

3 篇文章 0 订阅

由浅入深完整jQuery Pagination示例:完整demo

Pagination  是jQuery的ajax分页插件。使用一次性加载,故分页切换时无刷新与延迟。数据量较大时不太建议用此方法,因为加载会比较慢。

这里分享了jQuery Pagination Plugin的使用,以及扩展加入总页数和跳转功能,欢迎大家一起讨论。

1.jQuery Pagination Plugin的使用。

导入两个js文件:jquery.min.js和jquery.pagination.js。分页的方法是pagination.例如

		$("#Pagination").pagination(100);

这里100表示显示项目的总个数,这个参数时必须的。效果图如下:


2.加入总页数和跳转功能的扩展。

首先在jquery.pagination.js中加入一些参数,如下所示:

	opts = jQuery.extend({
		items_per_page:10,
		num_display_entries:10,
		current_page:0,
		num_edge_entries:0,
		link_to:"#",
		prev_text:"Prev",
		next_text:"Next",
		jump_text:"Jump",
		isSum:true,
		isJump:true,
		jump_format_text:"The number format error",
		jump_outofrange_text:"The number is out of range",
		jump_null_text:"The number is not allow null",
		ellipse_text:"...",
		prev_show_always:true,
		next_show_always:true,
		callback:function(){return true;}
	},opts||{});

然后找到并修改drawLinks方法。

在分页条的最前面加入总条数,在最后面加入跳转页码输入文本框和跳转链接。

			// sum total
			if(opts.isSum){
				panel.append("<a>共 "+maxentries+" 条记录</a>");
			}
			if(opts.isJump){
				// Generate Jump Input
				panel.append(jQuery("<input type='text' id='jump-index' maxlength='4'/>"));
				// Generate Jump Handler
				var index = null;
				var jump = jQuery("<a>"+opts.jump_text+"</a>").bind("click",function(evt){
					var jumpinput = jQuery("#jump-index");
					index = jumpinput.val();
					if(index == null || index == ""){
						alert(opts.jump_null_text);
						return;
					}
					if(/^\d+$/.test(index)){
						if(index > numPages() || index < 1){
							alert(opts.jump_outofrange_text);
							jumpinput.val("");
							return;
						}
						index-=1;
						return pageSelected(index,evt);
					}else{
						alert(opts.jump_format_text);
						jumpinput.val("");
						return;
					}
				}).attr("href", opts.link_to.replace(/__id__/,index));
				panel.append(jump);
			}

完整的drawLinks方法如下所示:
		/**
		 * 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);
			}
			// sum total
			if(opts.isSum){
				panel.append("<a>共 "+maxentries+" 条记录</a>");
			}
			// 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"});
			}
			if(opts.isJump){
				// Generate Jump Input
				panel.append(jQuery("<input type='text' id='jump-index' maxlength='4'/>"));
				// Generate Jump Handler
				var index = null;
				var jump = jQuery("<a>"+opts.jump_text+"</a>").bind("click",function(evt){
					var jumpinput = jQuery("#jump-index");
					index = jumpinput.val();
					if(index == null || index == ""){
						alert(opts.jump_null_text);
						return;
					}
					if(/^\d+$/.test(index)){
						if(index > numPages() || index < 1){
							alert(opts.jump_outofrange_text);
							jumpinput.val("");
							return;
						}
						index-=1;
						return pageSelected(index,evt);
					}else{
						alert(opts.jump_format_text);
						jumpinput.val("");
						return;
					}
				}).attr("href", opts.link_to.replace(/__id__/,index));
				panel.append(jump);
			}
		}
3.应用

如下是html页面的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link href="pagination.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="core.js"></script>
        <script src="pagination.js" type="text/javascript"></script>
        
        <!-- Load data to paginate -->
        <script type="text/javascript" src="data.js"></script>
        
        <script type="text/javascript">
            
            // This file demonstrates the different options of the pagination plugin
            // It also demonstrates how to use a JavaScript data structure to 
            // generate the paginated content and how to display more than one 
            // item per page with items_per_page.
                    
            /**
             * Callback function that displays the content.
             *
             * Gets called every time the user clicks on a pagination link.
             *
             * @param {int}page_index New Page index
             * @param {jQuery} jq the container with the pagination links as a jQuery object
             */
			function pageselectCallback(page_index, jq){
                // Get number of elements per pagionation page from form
                var items_per_page = $('#items_per_page').val();
                var max_elem = Math.min((page_index+1) * items_per_page, members.length);
                var newcontent = '';
                
                // Iterate through a selection of the content and build an HTML string
                for(var i=page_index*items_per_page;i<max_elem;i++)
                {
                    newcontent += '<dt>' + members[i][0] + '</dt>';
                    newcontent += '<dd class="state">' + members[i][2] + '</dd>';
                    newcontent += '<dd class="party">' + members[i][3] + '</dd>';
                }
                
                // Replace old content with new content
                $('#Searchresult').html(newcontent);
                
                // Prevent click eventpropagation
                return false;
            }
            
            // The form contains fields for many pagiantion optiosn so you can 
            // quickly see the resuluts of the different options.
            // This function creates an option object for the pagination function.
            // This will be be unnecessary in your application where you just set
            // the options once.
            function getOptionsFromForm(){
                var opt = {callback: pageselectCallback};
                // Collect options from the text fields - the fields are named like their option counterparts
                $("input:text").each(function(){
                    opt[this.name] = this.className.match(/numeric/) ? parseInt(this.value) : this.value;
                });
                // Avoid html injections in this demo
                var htmlspecialchars ={ "&":"&", "<":"<", ">":">", '"':"""}
                $.each(htmlspecialchars, function(k,v){
                    opt.prev_text = opt.prev_text.replace(k,v);
                    opt.next_text = opt.next_text.replace(k,v);
                })
                return opt;
            }
			
            // When document has loaded, initialize pagination and form 
            $(document).ready(function(){
            	// sum total
            	var length = members.length;
				// Create{} pagination element with options from form
				var optInit = getOptionsFromForm();
	            $("#Pagination").pagination(length, optInit);
	            // 按钮事件
	            $("#setoptions").click(function(){
	            	var opt = getOptionsFromForm();
	            	// 重新创建分页参数
	            	$("#Pagination").pagination(length,opt);
	            });
           });
            
        </script>
        <style type="text/css">
         <!--
        * {
            padding: 0;
            margin: 0;
        }
        body {
            background-color: #fff;
            margin: 20px;
            padding: 0;
            height: 100%;
            font-family: Arial, Helvetica, sans-serif;
        }
		
		h1 {
			margin-bottom:10px;
			font-size:1.5em;
		}
        
        h3 {
			margin-top:10px;
			font-size:1em;
		}
        
		#Searchresult {
			margin-top:15px;
			margin-bottom:15px;
			border:solid 1px #eef;
			padding:5px;
			background:#eef;
            width:40%;
		}
        
        #Searchresult dt {
            font-weight:bold;
        }
        
        #Searchresult dd {
            margin-left:25px;
        }
		
		#footer {
			margin-top:20px;
			font-size:60%;
			color:#15B;
		}
		
		label {
			float:left;
			width:250px;
			display:block;
		}
		
		form p {
			clear:both;
		}
		
        -->
        </style>
		
        <title>Pagination</title>
    </head>
    <body>
    	<h1>jQuery Pagination Plugin Demo</h1>
        <div id="Pagination" class="pagination">
        </div>
		<br style="clear:both;" />
        <h3>List of former members of the United States House of Representatives (A)</h3>
		<dl id="Searchresult">
			<dt>Search Results will be inserted here ...</dt>
		</dl>
        <h3>Config form for pagination parameters</h3>
        <!-- This form is just to demonstrate the whole range of options and display styles. -->
		<form name="paginationoptions">
			<p><label for="items_per_page">Number of items per page</label><input type="text" value="5" name="items_per_page" id="items_per_page" class="numeric"/></p>
			<p><label for="num_display_entries">Number of pagination links shown</label><input type="text" value="10" name="num_display_entries" id="num_display_entries" class="numeric"/></p>
			<p><label for="num">Number of start and end points</label><input type="text" value="2" name="num_edge_entries" id="num_edge_entries" class="numeric"/></p>
			<p><label for="prev_text">"Previous" label</label><input type="text" value="Prev" name="prev_text" id="prev_text"/></p>
			<p><label for="next_text">"Next" label</label><input type="text" value="Next" name="next_text" id="next_text"/></p>
			<input type="button" id="setoptions" value="Set options" />
		</form>
		<div id="footer">
			Copyright &copy; 2008-2009 by <a href="http://www.d-scribe.de/">describe europe Ltd.</a>.
		</div>
    </body>
</html>
在data.js里面是加载的数据定义了一个json数组变量members。通过getOptionsFromForm方法的到分页参数,在getOptionsFromForm中调用回调函数,加载分页内容。回调函数有两个参数,一个是page_index,另一个是jq,前一个表示您当前点击的那个分页的页数索引值,后一个参数表示装载容器。这里的页数索引值是关键,我们要根据这个索引值找到对应的(例如)members中的元素,然后再指定的容器中显示出来,demo中提供了装载单元素以及多元素的方法,相信不会有太大问题。

最终效果如图所示


4.参考文献:

http://blog.csdn.net/shadowsick/article/details/8570591

http://www.zhangxinxu.com/wordpress/2010/01/jquery-pagination-ajax%E5%88%86%E9%A1%B5%E6%8F%92%E4%BB%B6%E4%B8%AD%E6%96%87%E8%AF%A6%E8%A7%A3/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zerlinda_Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值