$ (Function (){
// Store the content of each TD in the click column;
Var aTdCont = [];
// Click the index value of the column
Var thi = 0
// Sort TR again
Var setTrIndex = function (tdIndex ){
For (I = 0; I <aTdCont. length; I ++ ){
Var trCont = aTdCont [I];
$ ("Tbody tr"). each (function (){
Var thisText = $ (this). children ("td: eq (" + tdIndex + ")"). text ();
If (thisText = trCont ){
$ ("Tbody"). append ($ (this ));
}
});
}
}
// Compare the function parameter functions
Var compare_down = function (a, B ){
Return a-B;
}
Var compare_up = function (a, B ){
Return B-;
}
// Comparison Function
Var fSort = function (compare ){
ATdCont. sort (compare );
}
// Retrieve the TD value, store it in the array, and retrieve the first two TD values;
Var fSetTdCont = function (thIndex ){
$ ("Tbody tr"). each (function (){
Var tdCont = $ (this). children ("td: eq (" + thIndex + ")"). text ();
ATdCont. push (tdCont );
});
}
// The function to be executed when you click
Var clickFun = function (thindex ){
ATdCont = [];
// Obtain the index value of the current column.
Var nThCount = thindex;
// Call the sortTh function to retrieve the data to be compared
FSetTdCont (nThCount );
}
// Click the event to bind the Function
$ ("Th"). toggle (function (){
Thi = $ (this). index ();
ClickFun (thi );
// Call the comparison function in descending order
FSort (compare_up );
// Re-Sort rows
SetTrIndex (thi );
}, Function (){
ClickFun (thi );
// Call the comparison function in ascending order
FSort (compare_down );
// Re-Sort rows
SetTrIndex (thi );
})
})
Main ideas:
Because JS has the SORT method to SORT the array, we will think of the array through a method.
1. When the table header is clicked, the column is clicked. That is, the index value of the column. This column is used for sorting. So I want to know the column of vertices.
2. For the data section of the table, that is, the value of the column to be clicked, store these values into an array.
3. SORT the array of stored data by SORT. (Two types are provided here: ascending or descending, because the sorting method needs to be switched during click. The first drop, the second drop, the third drop, and the fourth drop)
4. traverse the values of sorted arrays and compare them with the data in the TD column of the TR click column in each row during the traversal process. If they are equal, they are inserted at the end of the tbody. (the first line is inserted .)
DEMO download: http://www.bkjia.com/uploadfile/2012/0526/20120526090517272.zip
From Captain op