This article describes the implementation method of js header sorting. Share it for your reference.
The specific implementation method is as follows:
The code copy is as follows:
<script type="text/javascript">
// Whether to sort down
var isDescending = true;
/************************************************************
* The rows to be sorted must be placed in the <tbody></tbody> tag
* tableId: Sort table ID
* colNo: the sorted column number, that is, which column, starts from 0
* startRowNo: the starting line number of sorted, starting from 0
* sortLength: the number of rows to sort,
* type: the type of the sorting column
*/
function sort(tableId, colNo, startRowNo, sortLength, type)
{
//If the number of rows to be sorted is 1 or 0, then no sorting operation is performed
if(sortLength<=1){
return;
}
var currTable = document.getElementById(tableId);
var theHeader = currTable.outerHTML.substring(0, currTable.outerHTML.indexOf('<TBODY>')+7)
var theFooter = currTable.outerHTML.substring(currTable.outerHTML.indexOf('</TBODY>')-8);
//The number of rows here is the number of rows that remove the header table and the table rows.
var theRows = new Array(sortLength);
//Collapse the data in the table
for(i=startRowNo; i<sortLength+startRowNo; i++)
{
theRows[i-startRowNo] = new Array(currTable.rows[i].cells[colNo].innerText.toLowerCase(), currTable.rows[i].outerHTML);
}
if(type.toUpperCase()=='NUMBER')
{
theRows.sort(compareNumber);
}
else if(type.toUpperCase()=='DATE')
theRows.sort(compareDate);
else if(type.toUpperCase()=='STRING')
theRows.sort(compareString);
var tableInfo=''
for(j=0; j<theRows.length; j++)
{
tableInfo+=theRows[j][1];
}
isDescending = !isDescending;
currTable.outerHTML= theHeader + tableInfo + theFooter;
return ;
}
//Compare numbers
function compareNumber(x, y)
{
//Convert currency format data
a = x[0].excludeChars(",").trim();
b = y[0].excludeChars(",").trim();
if(a==""){a=0;}
if(b==""){b=0;}
if(isDescending)
{
return parseFloat(b) - parseFloat(a);
}
else
{
return parseFloat(a) - parseFloat(b);
}
}
//Compare strings
function compareString(x, y)
{
if(isDescending)
{
if(x[0]>y[0]) return -1;
else if(x[0]<y[0]) return 1;
else return 0;
}
else
{
if(x[0]<y[0]) return -1;
else if(x[0]>y[0]) return 1;
else return 0;
}
}
//Compare time
function compareDate(x,y){
var arr=x[0].split("-");
var starttime=new Date(arr[0],arr[1],arr[2]);
var starttimes=starttime.getTime();
var arrrs=y[0].split("-");
var lktime=new Date(arrs[0],arrs[1],arrs[2]);
var lktimes=lktime.getTime();
if(isDescending)
{
return lktimes - starttimes;
}
else
{
return starttimes - lktimes;
}
}
//Remove all specified strings in the string
String.prototype.excludeChars = function(chars){
var matching = new RegExp(chars , "g");
return this.replace(matching , '') ;
}
</script>
I hope this article will be helpful to everyone's JavaScript programming.