代码:
/*
* zhanjh 2008.06.04
*/
function XTableSort(){
this.table=null;
this.thead=null;
this.tbody=null;
this.rowsArray=[];
}
XTableSort.prototype={
setTableById:function(id){
var table=document.getElementById(id);
this.setSortTable(table);
},
setSortTable:function(table){
this.table=table;
this.thead=table.tHead;
this.tbody=table.tBodies[0];
this._initialize();
},
_initialize:function(){
var cells=this.thead.rows[0].cells;
for(var i=0;i<cells.length;i++){
var cell=cells[i];
cell.style.cursor="pointer";
cell.index=i;
cell.desc=false;
cell.style.backgroundColor="#cccccc";
var othis=this;
cell.οnclick=function(){
othis._tableSort(this.index,this.desc);
this.desc=!this.desc;
}
}
},
_tableSort:function(index,desc){
var trows=[];
var rows=this.tbody.rows;
for(var i=0;i<rows.length;i++){
trows.push(rows[i]);
}
trows.sort(this._generateCompare(index,desc));
for(var j=0;j<trows.length;j++){
this.tbody.appendChild(trows[j]);
}
},
_generateCompare:function(index,desc){
return function comparison(tr1,tr2){
var cell1=tr1.cells[index];
var cell2=tr2.cells[index];
var value1;
var value2;
value1= cell1.firstChild.value;
value2= cell2.firstChild.value;
var type="";
if(!value1){
value1=cell1.innerHTML;
}
if(!value2)
value2=cell2.innerHTML;
var result=0;
result= value1.localeCompare(value2)
if(desc)
return result;
else
return -result;
};
}
}
使用:
var sorter=new XTableSort();
function tableSort(){
var table=document.getElementById("tableId");
sorter.setSortTable(table);
}
参考资料
http://hi.baidu.com/zhanjh/blog/item/b2bb81cb9b7ce9f853664f6a.html