排序代碼
複製代碼 代碼如下: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: <meta charset="utf-8"><br /><style type="text/css"> table{ border-collapse:collapse; } table thead tr{ cursor:pointer; background:#EEE; } td{ border:1px solid #CCC; padding:10px; } </style><p><br /><table id="tblSort"><thead><tr><td>Last Name</td><td>First Name</td><td>Number</td><td>Score</td><td>Birthday</td></tr></thead><tbody><tr><td>O</td><td>D</td><td>5</td><td>20.1</td><td>7/12/1999</td></tr><tr><td>P</td><td>C</td><td>3</td><td>30.1</td><td>7/12/1990</td></tr><tr><td>Q</td><td>B</td><td>4</td><td>27.1</td><td>7/12/1995</td></tr><tr><td>R</td><td>A</td><td>2</td><td>24.1</td><td>7/12/1998</td></tr></tbody></table><p>