排序代码
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 parsFloat(sValue);
case "date":
새 Date(sValue)를 반환합니다.
기본값:
sValue.toString()을 반환합니다.
}
},
generateCompareTRs:function(iCol, sDataType, that){
반환 함수 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{
0을 반환합니다.
}
};
},
sort:function(){
for(var i=0,l=this.colDataRows.length;ithis.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;ioFragment.appendChild(this.aTRs[i]);
}
this.oTBody.appendChild(oFragment);
this.oTable.sortCol = this.iCol;
}
}
调用示例
함수 binSortTable(sTableID, iCol, sDataType){
var table=document.getElementById(sTableID),
ftr=table.tHead.rows[0],
tds=ftr .셀;
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,"날짜");
}
完整데모:
]
작성자:Artwl 출처: http://artwl.cnblogs.com