无为清净楼资源网 Design By www.qnjia.com
排序代码
复制代码 代码如下:
function SortTable(sTableID, iCol, sDataType){
this.oTable=document.getElementById(sTableID);
this.oTBody=this.oTable.tBodies[0];
this.colDataRows=this.oTBody.rows;
this.aTRs=[];
this.iCol=iCol;
this.sDataType=sDataType;
}
SortTable.prototype={
convert:function(sValue, sDataType){
switch(sDataType){
case "int":
return parseInt(sValue);
case "float":
return parseFloat(sValue);
case "date":
return new Date(sValue);
default:
return sValue.toString();
}
},
generateCompareTRs:function(iCol, sDataType, that){
return function compareTRs(oTR1,oTR2){
var vValue1= that.convert(oTR1.cells[iCol].firstChild.nodeValue, sDataType),
vValue2= that.convert(oTR2.cells[iCol].firstChild.nodeValue, sDataType);
if(vValue1 < vValue2){
return -1;
} else if(vValue1 > vValue2){
return 1;
} else{
return 0;
}
};
},
sort:function(){
for(var i=0,l=this.colDataRows.length;i<l;i++){
this.aTRs.push(this.colDataRows[i]);
}
if(this.oTable.sortCol === this.iCol){
this.aTRs.reverse();
} else {
this.aTRs.sort(this.generateCompareTRs(this.iCol, this.sDataType, this));
}
var oFragment=document.createDocumentFragment();
for(var i=0,l=this.aTRs.length;i<l;i++){
oFragment.appendChild(this.aTRs[i]);
}
this.oTBody.appendChild(oFragment);
this.oTable.sortCol = this.iCol;
}
}

调用示例
复制代码 代码如下:
function bindSortTable(sTableID, iCol, sDataType){
var table=document.getElementById(sTableID),
ftr=table.tHead.rows[0],
tds=ftr.cells;
if(tds[iCol]){
tds[iCol].onclick=function(){
var sortTable=new SortTable(sTableID, iCol, sDataType);
sortTable.sort();
}
}
}
window.onload=function(){
bindSortTable("tblSort",0);
bindSortTable("tblSort",1);
bindSortTable("tblSort",2,"int");
bindSortTable("tblSort",3,"float");
bindSortTable("tblSort",4,"date");
}

完整Demo:

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]
作者:Artwl
出处:http://artwl.cnblogs.com
标签:
js表格排序

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com