JavaScript sort table Sorting _javascript tips

Source: Internet
Author: User
1. Do you really know the sort method in JavaScript?
2. Do you know the function body of the Localecompare method in JavaScript?
3. What are the parameters of the table sorting method?
The sort method in JavaScript directly provides the function of sorting, without having to write a loop of our own to judge. But the mechanism is still the same,
Copy Code code as follows:

Window.onload=function () {
var myarr=new Array ("Red", "green", "Gray");
Myarr.sort ();
Alert (myarr.tostring ());
}

The result of the output is gray,green,red; What if it's an integer?
Copy Code code as follows:

Window.onload=function () {
var myarr=new Array (2,25,7);
Myarr.sort ();
Alert (myarr.tostring ());
}

If you think it's 2,7,25, then it's nice to say you're wrong, and the result is 2,25,7, why? Because the sort method is judged by the ASCII character of the string, any non-string will first be converted to a string,
As a result, the above situation arises. So what do I do with the integer sort? Conversion Bai, very simple, but if there are float,date, and so on? All the same, write a conversion function can not get. You have to do what you say.
Copy Code code as follows:

function Convert (datavalue,datatype) {
Switch (DataType) {
Case "int":
return parseint (DataValue);
Case "float":
return parsefloat (DataValue);
Case "Date":
return new Date (Date.parse (DataValue));
Default
return datavalue.tostring ();
}
}

A very simple conversion method came out, you notice date, because it is an object, so unlike the basic type, each time a new object is generated.
The Sort method can have a parameter of sortfunction,
Let's look at a simple sorting method.
Copy Code code as follows:

function Compare_function (value1,value2) {
if (value1<value2)
return-1;
else if (value1>value2)
return 1;
Else
return 0;
}

In fact, the Localecompare function is similar. When value1 is less than value2, return-1, that is, order, will be value1<value2, return 1, that is, reverse-time sorting.
Back to the point, to sort the table, click on the table head can be sorted, then there must be a method, take it as sorttable, that to the table of a column of the sort, what parameters to have? First you need a table ID to determine which table, its secondary
Determine which column to sort, and the last column of data is not necessarily a string, so you want a parameter of a data type, i.e. sorttable (Tableid,col,datatype);
Copy Code code as follows:

var Dtable=document.getelementbyid (TableID);
var dbody=dtable.tbodies[0];
var datarows=dbody.rows;
var myarr=new Array;
Put all rows in an array
for (Var i=0;i<datarows.length;i++) {
Myarr[i]=datarows[i];
}
Myarr.sort (Customcompare (Col,datatype));
Create a fragment of the document, add all the rows in, the equivalent of a scratch shelf, the purpose is (if directly added to the document.body inside, will insert a row, refresh once, if more data will affect the user experience)
Place all the rows in the staging frame, and then add the rows in the staging frame together to the document.body so that the table is refreshed only once.
Just like when you go to a store to shop, all the items you're going to buy are written on the list (document fragments), and then the supermarket buys all of it and doesn't think about one thing at a time,
var frag=document.createdocumentfragment ();
for (Var i=0;i<myarr.length;i++) {
Frag.appendchild (Myarr[i]); Add all the rows in the array to the document fragment
}
Dbody.appendchild (Frag);//Add all the lines in the document fragment to the body

This completes a sort, and then there is a customcompare function, a custom sort method that serves as a parameter to the sort method, two arguments, one for the sorted column and one for the data type.
function body is
Copy Code code as follows:

return function Comparetrs (TR1,TR2) {
var value1,value2;
Value1=convert (Tr1.cells[col].firstchild.nodevalue,datatype);
Value2=convert (Tr2.cells[col].firstchild.nodevalue,datatype);
if (value1 < value2)
return-1;
else if (value1 > value2)
return 1;
Else
return 0;
};

Of course, it can be written in such a way as to be given by the closures. Iterate through each item in the array in the Sort method (each item is stored with each row of table) and passes the argument to Comparetrs (TR1,TR2) and returns the result.
In fact this is OK, but what if you want to sort the picture?
What type of picture is it? I don't know, so let's take a look at the title of the picture, or the Alt attribute, which can always be a string. Give them a custom attribute customvalue, and then sort it by its value. Just when it comes to being true.
To determine if this property is included, you must modify the Comparetrs method.
Copy Code code as follows:

function Customcompare (col,datatype) {
return function Comparetrs (TR1,TR2) {
var value1,value2;
Judge whether there is customvalue this attribute
if (Tr1.cells[col].getattribute ("Customvalue")) {
Value1=convert (Tr1.cells[col].getattribute ("Customvalue"), DataType);
Value2=convert (Tr2.cells[col].getattribute ("Customvalue"), DataType);
}
else{
Value1=convert (Tr1.cells[col].firstchild.nodevalue,datatype);
Value2=convert (Tr2.cells[col].firstchild.nodevalue,datatype);
}
if (value1 < value2)
return-1;
else if (value1 > value2)
return 1;
Else
return 0;
};
}

The order of the pictures was also solved. So how many times do you want to order a user? Do we have to revise the Comparetrs method?
Obviously unwanted, there is a reverse () method in JavaScript that can reverse each item in the array. The modification of the SortTable method is only so
Copy Code code as follows:

function SortTable (tableid,col,datatype) {
var Dtable=document.getelementbyid (TableID);
var dbody=dtable.tbodies[0];
var datarows=dbody.rows;
var myarr=new Array;
for (Var i=0;i<datarows.length;i++) {
Myarr[i]=datarows[i];
}
Determines whether the last sorted column is the same column this time
if (Dbody.currentcol==col) {
Myarr.reverse (); To invert an array
}
else{
Myarr.sort (Customcompare (Col,datatype));
}
Create a fragment of the document, add all the rows in, the equivalent of a scratch shelf, the purpose is (if directly added to the document.body inside, will insert a row, refresh once, if more data will affect the user experience)
Place all the rows in the staging frame, and then add the rows in the staging frame together to the document.body so that the table is refreshed only once.
Just like when you go to a store to shop, all the items you're going to buy are written on the list (document fragments), and then the supermarket buys all of it and doesn't think about one thing at a time,
var frag=document.createdocumentfragment ();
for (Var i=0;i<myarr.length;i++) {
Frag.appendchild (Myarr[i]); Add all the rows in the array to the document fragment
}
Dbody.appendchild (Frag);//Add all the lines in the document fragment to the body
Dbody.currentcol=col; Record the currently sorted column
}

The capitalization in JavaScript must be noted and error prone.
The above code test success, the date of the order, the effect as shown

All code:
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title> Table Sorting </title>
<script type= "Text/javascript" >
var isasc=true;
function SortTable (tableid,col,datatype) {
var Imgsort=document.getelementbyid (' col ' +col);
Whether the judgment is in reverse or in order
if (isasc==true) {
imgsort.src= ' img/arrow_small_down.png ';
}
else{
imgsort.src= ' img/arrow_small_up.png ';
}
isasc=! ISASC;
var Dtable=document.getelementbyid (TableID);
var dbody=dtable.tbodies[0];
var datarows=dbody.rows;
var myarr=new Array;
for (Var i=0;i<datarows.length;i++) {
Myarr[i]=datarows[i];
}
Determines whether the last sorted column is the same column this time
if (Dbody.currentcol==col) {
Myarr.reverse (); To invert an array
}
else{
Myarr.sort (Customcompare (Col,datatype));
}
Create a fragment of the document, add all the rows in, the equivalent of a scratch shelf, the purpose is (if directly added to the document.body inside, will insert a row, refresh once, if more data will affect the user experience)
Place all the rows in the staging frame, and then add the rows in the staging frame together to the document.body so that the table is refreshed only once.
Just like when you go to a store to shop, all the items you're going to buy are written on the list (document fragments), and then the supermarket buys all of it and doesn't think about one thing at a time,
var frag=document.createdocumentfragment ();
for (Var i=0;i<myarr.length;i++) {
Frag.appendchild (Myarr[i]); Add all the rows in the array to the document fragment
}
Dbody.appendchild (Frag);//Add all the lines in the document fragment to the body
Dbody.currentcol=col; Record the currently sorted column
}
function Customcompare (col,datatype) {
return function Comparetrs (TR1,TR2) {
var value1,value2;
Judge whether there is customvalue this attribute
if (Tr1.cells[col].getattribute ("Customvalue")) {
Value1=convert (Tr1.cells[col].getattribute ("Customvalue"), DataType);
Value2=convert (Tr2.cells[col].getattribute ("Customvalue"), DataType);
}
else{
Value1=convert (Tr1.cells[col].firstchild.nodevalue,datatype);
Value2=convert (Tr2.cells[col].firstchild.nodevalue,datatype);
}
if (value1 < value2)
return-1;
else if (value1 > value2)
return 1;
Else
return 0;
};
}
function Convert (datavalue,datatype) {
Switch (DataType) {
Case "int":
return parseint (DataValue);
Case "float":
return parsefloat (DataValue);
Case "Date":
return new Date (Date.parse (DataValue));
Default
return datavalue.tostring ();
}
}
</script>
<body>
<div id= "Container" >
<table border= "1" id= "MyTable" >
<thead>
<tr>
&LT;TD onclick= "sorttable (' MyTable ', 0, ' string ')" style= "Cursor:pointer" > Picture sort </td>
&LT;TD onclick= "sorttable (' MyTable ', 1, ' int ')" style= "Cursor:pointer" > Integer sort </td>
&LT;TD onclick= "sorttable (' MyTable ', 2, ' float ')" style= "Cursor:pointer" > Floating-point order </td>
&LT;TD onclick= "sorttable (' MyTable ', 3, ' string ')" style= "Cursor:pointer" > String sorting </td>
&LT;TD onclick= "sorttable (' MyTable ', 4, ' Date ')" style= "Cursor:pointer" > Date sort </td>
</tr>
</thead>
<tbody>
<tr>
&LT;TD customvalue= "Doc" >
</td>
<td>2</td>
<td>5.4</td>
<td>zd</td>
<td>2009-10-31 14:33:13</td>
</tr>
<tr>
&LT;TD customvalue= "Zip" >
</td>
<td>267</td>
<td>8.9</td>
<td>xx</td>
<td>2002-10-31 14:36:13</td>
</tr>
<tr>
&LT;TD customvalue= "XLT" >
</td>
<td>6</td>
<td>60.4</td>
<td>ty</td>
<td>2009-10-31 19:33:13</td>
</tr>
<tr>
&LT;TD customvalue= "TXT" >
</td>
<td>9</td>
<td>0.8</td>
<td>lp;</td>
<td>2004-5-31 14:33:13</td>
</tr>
<tr>
&LT;TD customvalue= "Doc" >
</td>
<td>34</td>
<td>9.4</td>
<td>cv</td>
<td>1009-10-31 14:33:13</td>
</tr>
<tr>
&LT;TD customvalue= "TXT" >
</td>
<td>289</td>
<td>23.4</td>
<td>uio</td>
<td>2005-10-31 14:33:13</td>
</tr>
<tr>
&LT;TD customvalue= "Zip" >
</td>
<td>45</td>
<td>89.4</td>
<td>cb</td>
<td>1039-10-31 14:33:13</td>
</tr>
<tr>
&LT;TD customvalue= "Doc" >
</td>
<td>2</td>
<td>5.4</td>
<td>zd</td>
<td>2009-10-31 14:33:13</td>
</tr>
<tr>
&LT;TD customvalue= "TXT" >
</td>
<td>42</td>
<td>9.3</td>
<td>bm</td>
<td>1069-10-31 14:34:14</td>
</tr>
</tbody>
</table>
</div>
</body>

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.