JavaScript Operations Table Sorting

Source: Internet
Author: User

Table sorting, the general approach is to pass the sorted fields to the background to requery and sort, JavaScript can also do a simple table sorting, Memo code:

Type converter, which converts the column's field type to a type that can be sorted: string,int,float
function convert (svalue, Sdatatype) {
Switch (sdatatype) {
Case "int":
return parseint (svalue);
Case "float":
return parsefloat (svalue);
Case "Date":
return new Date (Date.parse (svalue));
Default
return svalue.tostring ();
        
}
}
      
Sort function Generator, Icol represents the column index, Sdatatype represents the data type of the column
function Generatecomparetrs (Icol, Sdatatype) {
    
return function Comparetrs (oTR1, oTR2) {
var vValue1 = convert (Otr1.cells[icol].firstchild.nodevalue, sdatatype);
var vValue2 = convert (Otr2.cells[icol].firstchild.nodevalue, sdatatype);
    
if (VValue1 < vValue2) {
return-1;
else if (vValue1 > VValue2) {
return 1;
} else {
return 0;
}
};
}
      
Sorting method
function sorttable (Stableid, Icol, Sdatatype) {
var otable = document.getElementById (Stableid);
var otbody = otable.tbodies[0];
var coldatarows = otbody.rows;
var atrs = new Array;
        
Put all columns into an array
for (Var i=0 i < coldatarows.length; i++) {
Atrs[i] = coldatarows[i];
}
        
To determine if the last sorted column is the same as the column you are sorting now, use the reverse () reverse order directly
if (Otable.sortcol = = Icol) {
Atrs.reverse ();
} else {
Using the sort method of an array to pass the sort function
Atrs.sort (Generatecomparetrs (Icol, Sdatatype));
}
    
var ofragment = document.createdocumentfragment ();
for (Var i=0 i < atrs.length; i++) {
Ofragment.appendchild (Atrs[i]);
}
   
Otbody.appendchild (ofragment);
Record the last sorted column index
Otable.sortcol = Icol;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.