自己写的第一个jquery插件,起名字叫amsetpager。暂定为第一个版本吧,哈哈。
目前实现三种分页吧,一个是普通的通过url按当前页向后台查询数据展示,一种是所有的数据查询完毕进行分页。然后就是通过回调函数进行ajax展示数据。测试ie6好像也没问题。
首先我的js一般,可能代码有些臃肿,有些地方可能代码不是写的好。但是我会努力的,只要大家提提意见哈。
下面是三个例子的集合(asp.net做的一个页面):
首先是css代码:
<style type="text/css">
.pager a{ text-decoration: none; border: 1px solid #e7ecf0;color: #15B;}
.pager a:hover{ background-color:#E6EBEF}
.pager a,.pager span{display: inline-block;padding: 0.1em 0.4em;margin-right: 5px; margin-bottom: 5px;}
.selectno{background: #26B;color: #fff;border: 1px solid #AAE;}
</style>
.pager是分页的容器的class,.selectno就是选中页class。
然后js代码:
<script type="text/javascript"> $(function () { //url分页 $("#tab_url").AmSetPager({ 'pagerName': 'pager1', 'mode': 'url', 'dataCount': '<%=DataCount %>', //后台获取总条数 'viewCount': '<%=viewCount %>', //配置每页显示 'listCount': 6, //默认模板此值不能小于5 'urlparameter': 'type=3&d=22' //最后一个参数是你其他的查询参数,没有的话就不用添加 }); //静态的分页 $("#tab_static").AmSetPager({ 'pagerName': 'pager2', 'mode': 'static', 'viewCount': 5, 'listCount': 9 }); //回调的分页(mode选ajax,static也行--那静态分页也没效果了) $("#tab_ajax").AmSetPager({ 'pagerName': 'pager3', 'mode': 'ajax', 'dataCount': '<%=DataCount %>', //后台获取总条数 'viewCount': '<%=viewCount %>', //配置每页显示 'listCount': 7, 'callback': function (e, i, c) { //分别代表e:数据父容器,i:当前页,c:每页显示多少条数据 e.html('loding...'); //就是加个效果 $.getJSON("getdata.ashx", { "index": i, "count": c }, function (data) { e.html(''); //先清空遗留数据 for (var i = 0; i < data.length; i++) { e.append("<li>" + data[i] + "......</li>"); } }) } }); }) </script>
主要一些配置参数(有些可配置的直接写在代码里了,做的不是很好,以后会改的)
pagerName: "pager", //分页的容器viewCount: 5, //可显示多少条数据dataCount: 0, //如果后台取数据,总数多少(静态的不用)selectClass: "selectno", //选中的样式listCount:10, //显示多少个分页码(不包括前一页,后一页)enablePrevNext:true, //允许显示前一页后一页enableFirst:true, //允许只有一页的情况下显示页码template:"default", //模板(现只有default) mode:"static", //"url" or "ajax"urlparameter:"", //url参数,后面aa=1&bb=2...callback:null //回调函数(ajax取数据或者静态也可以使用)
下面是三个分页的html代码:
<div style=" border:1px solid blue; margin:10px;padding:5px"> <h3>url分页,就是后台查询数据根据url参数分页</h3> <table id="tab_url"> <asp:Repeater ID="repurl" runat="server"> <ItemTemplate> <tr><td><%#Eval("UName") %></td><td><%#Eval("Age") %></td></tr> </ItemTemplate> </asp:Repeater> </table> <div id='pager1' class='pager'></div> </div> <div style=" border:1px solid gray; margin:10px; padding:5px"> <h3>static分页,就是查询完毕的静态数据,再进行分页</h3> <div id="tab_static"> <asp:Repeater ID="repstatic" runat="server"> <ItemTemplate> <div><%#Eval("UName") %><span>----------</span><%#Eval("Age") %></div> </ItemTemplate> </asp:Repeater> </div> <div id='pager2' class='pager'></div> </div> <div style=" border:1px solid red; margin:10px;padding:5px"> <h3>回调分页,用于ajax请求数据时,就是自行进行数据展示</h3> <ul id="tab_ajax"> <li>loding...</li> </ul> <div id='pager3' class='pager'></div> </div>
这个应该简单,就是可以使用table,ul或div里放什么元素。
然后就是后台模拟的简单的给repeater进行数据绑定(还有一个ashx文件,用于ajax方式的取数据)
View Code
1 protected int DataCount = 0;//总条数 2 protected int viewCount = 0;//每页显示几条 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 if (!IsPostBack) 6 { 7 int p = int.Parse(string.IsNullOrEmpty(Request.QueryString["p"])? "1" : Request.QueryString["p"]);//索引页 8 DataCount = GetDataCount(); 9 viewCount = 6;10 BindData(p,viewCount);//url分页数据11 BindTotalData(); //用于静态分页数据12 }13 }14 int GetDataCount()15 {16 //下面仅是示例17 return 50;18 }19 List<Users> GetData(int p,int v)20 {21 List<Users> list = new List<Users>();22 //下面仅是示例23 for (int i = 0; i < v; i++)24 {25 Users u = new Users();26 u.UName = p + "----"+i+"abc";27 u.Age = i + 1;28 list.Add(u);29 }30 return list;31 }32 List<Users> GetTotalData()33 {34 List<Users> list = new List<Users>();35 //下面仅是示例36 for (int i = 0; i < DataCount; i++)37 {38 Users u = new Users();39 u.UName = "----" + i + "abc";40 u.Age = i + 1;41 list.Add(u);42 }43 return list;44 }45 46 void BindData(int p,int v)47 {48 this.repurl.DataSource = GetData(p, v);49 this.repurl.DataBind();50 }51 void BindTotalData()52 { 53 this.repstatic.DataSource = GetTotalData();54 this.repstatic.DataBind();55 }56 class Users57 {58 public string UName { get; set; }59 public int Age { get; set; }60 }
View Code
1 /// <summary> 2 /// getdata 的摘要说明,这个是简单的ajax取数据 3 /// </summary> 4 public class getdata : IHttpHandler 5 { 6 7 public void ProcessRequest(HttpContext context) 8 { 9 context.Response.ContentType = "text/plain";10 int index = int.Parse(context.Request.QueryString["index"]);11 int count = int.Parse(context.Request.QueryString["count"]);12 List<string> list = new List<string>();13 for (int i = 0; i < count; i++)14 {15 list.Add(index.ToString() + new Random().Next(10000));16 }17 JavaScriptSerializer sl = new JavaScriptSerializer();18 context.Response.Write(sl.Serialize(list));19 context.Response.End();20 }21 22 public bool IsReusable23 {24 get25 {26 return false;27 }28 }29 }
完毕
那么先来看下这三种效果吧:
附源码:
分页插件的代码
/* * Project: AmSetPager * Description: a Plugin for creating page numbers * Author: ameol * License: v1.0 */;(function ( $, window, document, undefined ) { // Create the defaults once var pluginName = "AmSetPager", defaults = { pagerName: "pager", //分页的容器 viewCount: 5, //可显示多少条数据 dataCount: 0, //如果后台取数据,总数多少(静态的不用) selectClass: "selectno", //选中的样式 listCount:10, //显示多少个分页码(不包括前一页,后一页) enablePrevNext:true, //允许显示前一页后一页 enableFirst:true, //允许只有一页的情况下显示页码 template:"default", //模板(现只有default) mode:"static", //"url" or "ajax" urlparameter:"", //url参数,后面aa=1&bb=2... callback:null //回调函数(ajax取数据或者静态也可以使用) }; // The actual plugin constructor function Plugin( element, options ) { this.element = element; this.options = $.extend( {}, defaults, options ); //this._defaults = defaults; this._name = pluginName; this.init(); } //private //获取url参数 var getQueryString = function (name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return undefined; } //静态模板数据展示 var Bind_StaticData = function($content,minnum,maxnum) { if (minnum > 0) { $content.children(":gt(" + (minnum - 1) + "):lt(" + maxnum + ")").css("display", "block"); } else { $content.children(":lt(" + maxnum + ")").css("display", "block"); } $content.children(":lt(" + (minnum) + ")").css("display", "none"); $content.children(":gt(" + (maxnum - 1) + ")").css("display", "none"); } //主要 //创建SetPager类 var SetPager = function (options,pageCount){ this.op = options; this.pageCount = pageCount; } SetPager.prototype = { //格式化成a元素 FormatStr : function(pageNo, pageText) { var href = this.op.mode=='url'?location.pathname+"?"+this.op.urlparameter+"&p="+pageNo:"javascript:void(0);"; if (typeof (pageText) == "number") { return "<a href='"+href+"' >" + pageText + "</a>"; } return "<a href='"+href+"' i='" + pageNo + "'>" + pageText + "</a>"; }, //选中状态a元素 FormatStrIndex : function(pageNo){ return "<span class='"+this.op.selectClass+"'>" + pageNo + "</span>"; }, //默认模板初始化页码集合 InitDefaultList : function(_pageIndex){ if(this.op.listCount<5) throw new Error("listCount must be lager than 5"); //listCount>5 var pageIndex = parseFloat(_pageIndex); //转化为number var ns = new Array(); var numList = new Array(this.op.listCount); if (pageIndex >= this.op.listCount) { numList[0] = 1; numList[1] = "…"; var infront = 0; var inback = 0; var inflag = Math.floor((this.op.listCount-2)/2); if(this.op.listCount%2==0){ infront = inflag-1; inback = inflag; }else{ infront = inflag; inback = inflag; } if (pageIndex + inback >= this.pageCount) { for (i = this.pageCount - (this.op.listCount-3); i < this.pageCount + 1; i++) { ns.push(i); } for (j = 0; j <= (this.op.listCount-3); j++) { numList[j + 2] = ns[j]; } } for (i = pageIndex - infront; i <= pageIndex + inback; i++) { ns.push(i); } for (j = 0; j < (this.op.listCount-2); j++) { numList[j + 2] = ns[j]; } } else { if (this.pageCount >= this.op.listCount) { for (i = 0; i < this.op.listCount; i++) { numList[i] = i+1; } } else { for (i = 0; i < this.pageCount; i++) { numList[i] = i+1; } } } return numList; }, //生成页码 InitPager : function(pageIndex){ $("#"+this.op.pagerName).html(''); if(this.op.enableFirst==false&&this.pageCount<=1){ return null; } var array = new Array(); //var finalarr = new Array(); var $con = $("#"+this.op.pagerName); //var pageIndex = parseFloat(pageIndex); switch(this.op.template){ //选择模板 case 'default':array = this.InitDefaultList(pageIndex,this.pageCount);break; default:array = this.InitDefaultList(pageIndex,this.pageCount); } if(!array instanceof Array){ throw new Error("is not array"); } if(array.length!=this.op.listCount){ throw new Error("array.length error:"+array.length); } if(pageIndex>1&&this.op.enablePrevNext){ $con.append(this.FormatStr(pageIndex-1,'上一页')); } for(var i=0;i<array.length;i++){ if(typeof array[i]=='undefined'){ continue; } if(pageIndex==array[i]){ $con.append(this.FormatStrIndex(array[i])); }else if(typeof array[i]=='number'){ $con.append(this.FormatStr(array[i],array[i])); }else{ $con.append(array[i]); } } if(pageIndex<this.pageCount&&this.op.enablePrevNext){ $con.append(this.FormatStr(pageIndex+1,'下一页')); } //$("#"+this.op.pagerName).append(finalarr); } } Plugin.prototype = { //初始化 init: function() { var options = this.options; var $thisbase = $(this.element); var $content; if($thisbase.is(':has(tbody)')){ $content=$thisbase.children(); } else{ $content=$thisbase; } var count = options.mode=='static'?$content.children().length:options.dataCount; var eachcount = options.viewCount; var totalpage = Math.ceil(count / eachcount); var $pager = $("#"+options.pagerName); var setpager = new SetPager(options,totalpage); //init if(options.mode=='url'){ var urlindex = getQueryString("p"); if(isNaN(urlindex)){ setpager.InitPager(1); }else{ urlindex = parseFloat(urlindex); setpager.InitPager(urlindex>totalpage?totalpage:urlindex); } }else{ setpager.InitPager(1); if(options.mode=='static'&&typeof options.callback!='function'){ Bind_StaticData($content,0,eachcount); }else{ options.callback($content,1,options.viewCount); } $pager.bind("click",function(e){ //click事件 if(e.target.tagName!='A') return; var $this = $(e.target); $this.removeAttr("href").siblings().attr("href", "javascript:void(0);");//.. var indexnum = parseInt($this.html())==$this.html()?parseInt($this.html()):parseInt($this.attr('i')); var maxnum = (indexnum * eachcount); var minnum = (indexnum - 1) * eachcount; if(options.mode!='static'&&options.mode!='ajax'){ throw new Error("mode must be selected:static,url,ajax"); } if(options.mode=='static'&&typeof options.callback!='function'){ setpager.InitPager(indexnum); Bind_StaticData($content,minnum, maxnum); }else{ setpager.InitPager(indexnum); options.callback($content,indexnum,options.viewCount); } }); } } }; $.fn[pluginName] = function ( options ) { return this.each(function () { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin( this, options )); } }); };})( jQuery, window, document );
给个demo下载链接吧 点这里
<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>