jquery表格排序插件
网上找了个表格排序,不过升序和降序存在问题,排序时间不对,因此,写了一个表格排序插件
可以根据任意字段进行排序,由于是js排序,因此是无刷新,并且速度比较快
效果图:
默认使用例子:
参数名类型描述ascImgUrlstring升序图片地址descImgUrlstring降序图片地址endRowint最后一行(负数代表倒数第几行)isHeaderThboolean头部标题是否是th带html例子:
/** * jquery表格插件 * @author ZouHao * @param ascImgUrl 升序图片地址 * @param descImgUrl 降序图片地址 * 例子: * 1:默认使用语法 * $("table").sort(); * 2:参数使用语法 * $("table").sort({ * 'ascImgUrl':'/static/images/bullet_arrow_up.png','descImgUrl':'/static/images/bullet_arrow_down.png','endRow':0,//最后一行'isHeaderTh':true //头部是th或者td * }); */;(function ($) { $.fn.sort = function (options) { var settings = $.extend({'ascImgUrl':'/static/images/bullet_arrow_up.png', //升序图片'descImgUrl':'/static/images/bullet_arrow_down.png', //降序图片'endRow':0,//最后一行'isHeaderTh':true //头部是th或者td},options);init(this);function init(p){//初始化一些变量var node=settings.isHeaderTh?'th':'td';var trList=$(p).find("tr "+node+"[sort='true']");if(settings.endRow==0){settings.endRow=$(p).find("tr").size();}else if(settings.endRow<0){settings.endRow=$(p).find("tr").size()+settings.endRow;}else{settings.endRow=$(p).find("tr").size()-settings.endRow;}//初始化点击表格头部事件trList.click(function(){//获取当前行数settings.startRow=$(this).parent().index();settings.index=$(this).index();if($(this).find("img").size()==2){addImg(trList);removeImg(this,'asc');changeTableBody(p,'asc');}else{if($(this).find("img").attr("src")==settings.ascImgUrl){addImg(trList);removeImg(this,'desc');changeTableBody(p,'desc');}else{addImg(trList);removeImg(this,'asc');changeTableBody(p,'asc');}}});//初始化头部图片addImg(trList);}//将数据进行排序function changeTableBody(p,sort){data=new Array();//所选的行var trBodyList=$(p).find("tr:lt("+settings.endRow+"):gt("+settings.startRow+")");trBodyList.each(function(i){data[i]=new Array();$(this).find("td").each(function(j){data[i][j]=$(this).html();});});data.sort(function(x, y){ if(sort=='asc'){return x[settings.index].localeCompare(y[settings.index]); }else{return y[settings.index].localeCompare(x[settings.index]); }});trBodyList.each(function(i){$(this).find("td").each(function(j){$(this).html(data[i][j]);});});}/** * 为每个表格头部添加图片 */function addImg(trList){trList.find("img").remove();trList.append('<img src="'+settings.ascImgUrl+'" style="width:8px;height:8px;" /><img src="'+settings.descImgUrl+'" style="width:8px;height:8px;" />')}/** * 移出当前点击表格升序/降序图片 */function removeImg(p,sort){var imgUrl=sort=='desc'?settings.ascImgUrl:settings.descImgUrl;$(p).find("img").each(function(){if($(this).attr("src")==imgUrl){$(this).remove();return false;}});}}; })(jQuery);
demo:
下载地址:http://download.csdn.net/detail/zouhao619/5211792