$(function(){ //Save the content of each TD in the click column; var aTdCont = []; //Click the index value of the column var thi = 0 // re-sort TR 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)); } }); } } //parameter function of the comparison function var compare_down = function(a,b){ return a-b; } var compare_up = function(a,b){ return b-a; } //comparison function var fSort = function(compare){ aTdCont.sort(compare); } //Take out the value of TD, store it in the array, and take out the first two TD values; var fSetTdCont = function(thIndex){ $("tbody tr").each(function() { var tdCont = $(this).children("td:eq("+thIndex+")").text(); aTdCont.push(tdCont); }); } // function to be executed when clicked var clickFun = function(thindex){ aTdCont = []; //Get the index value of the clicked current column var nThCount = thindex; / / Call the sortTh function to take out the data to be compared fSetTdCont(nThCount); } //click event binding function $("th").toggle(function(){ thi= $(this).index(); clickFun (thi); //call comparison function, descending order fSort(compare_up); // reorder rows setTrIndex (thi); },function(){ clickFun (thi); //call the comparison function in ascending order fSort(compare_down); // reorder rows setTrIndex (thi); }) })
Main idea:
Because JS has the SORT method to sort the array, then through this method, we will think of the array.
1. When clicking on the table header, take out the column that was clicked. That is, the index value of the column. Because the following is the column to be sorted. So I need to know which column is the point.
2. For the data part of the table, that is, the tbody part, take the values of the clicked columns, and store these values in an array.
3. Sort the array of stored data by the SORT method. (Two types are written here, ascending, or descending, because it is the way to switch the sorting when clicking. The first descends, the second ascends, the third descends, the fourth ascends, and so on)
4. Traverse the values of the sorted array, and compare it with the data in the TD of the click column of each row of TR during the traversal process. If it is equal, it will be inserted at the end of the tbody. (The first inserted will be on the first row.)
demo download:
Original address: http://www.cnblogs.com/lufy/archive/2012/05/23/2515142.html
Reference address: http://www.cnblogs.com/wuzhsh/archive/2012/07/26/2609312.html