Sort code
Copy codeThe Code is as follows:
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;
}
}
Call example
Copy codeThe Code is as follows:
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 ");
}
Complete Demo:
<! DOCTYPE html> <pead> <meta charset = "UTF-8"/> <title> JSCode demo </title> <style type = "text/css"> table {border -collapse: collapse;} table thead tr {cursor: pointer; background: # EEE;} td {border: 1px solid # CCC; padding: 10px ;} </style> </pead> <body> <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> <td> P </td> <td> C </td> <td> 3 </td> <td> 30.1 </td> <td> 7/12/1990 </td> </tr> <td> Q </td> <td> B </td> <td> 4 </td> <td> 27.1 </td> <td> 7/12/1995 </td> </tr> <td> R </td> <td> A </td> <td> 2 </td> <td> 24.1 </td> <td> 7/12/1998 </td> </tr> </tbody> </table> </body> </ html>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Author: Artwl
Source: http://artwl.cnblogs.com