JavaScript Sort table sorting

Source: Internet
Author: User

1. Do you really understand the Sort method in JavaScript?
2. Do you know the function body of the localeCompare method in JavaScript?
3. What parameters are required for table sorting?
The sort method in JavaScript directly provides the sorting function, and we do not need to write a loop to judge one by one. But its mechanism is still like that,
Copy codeThe Code is as follows:
Window. onload = function (){
Var MyArr = new Array ("red", "green", "gray ");
MyArr. sort ();
Alert (MyArr. toString ());
}

The output result is gray, green, and red. What if it is an integer?
Copy codeThe Code is as follows:
Window. onload = function (){
Var MyArr = new Array (2, 25, 7 );
MyArr. sort ();
Alert (MyArr. toString ());
}

If you think it is, 25, you are very happy to say that you are wrong. The result is, 7. Why? Because the sort method is determined by the string ASCII, any non-string will be converted to a string first,
As a result, the above situation occurs. What should I do if I want to sort integers? Conversion is easy, but what if Float, Date, and so on? They are all the same. You cannot write a conversion function. You have to do it.
Copy codeThe Code is 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 simple conversion method comes out. Note that Date is an object, so a new object is generated every time different from the basic type.
The Sort method can have a parameter sortfunction,
First look at a simple sorting method
Copy codeThe Code is 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 to this function. When value1 is smaller than value2,-1 is returned, which is ordered. value1 <value2, returns 1, that is, reverse chronological sorting.
Back to the key point, you need to sort the table and click the table header to sort the table. There must be a method to retrieve the table as SortTable. Then you need to sort a column of the table, what parameters are required? First, you need a table ID to determine which table to use.
Determine the column to be sorted. The data in the last column is not necessarily a string. Therefore, a data type parameter, that is, SortTable (TableID, Col, DataType) is required );
Copy codeThe Code is as follows:
Var DTable = document. getElementById (TableID );
Var DBody = DTable. tBodies [0];
Var DataRows = DBody. rows;
Var MyArr = new Array;
// Put all rows into an array
For (var I = 0; I <DataRows. length; I ++ ){
MyArr [I] = DataRows [I];
}
MyArr. sort (CustomCompare (Col, DataType ));
// Create a File Fragment and add all rows to it. This is equivalent to a temporary storage shelf. The purpose is (if it is directly added to the document. in the body, a row is inserted and refreshed once. If there is more data, the user experience will be affected)
// First place all rows in the storage shelf, and then add the rows in the storage shelf together to document. body, so that the table will be refreshed only once.
// Just like when you go to the store for shopping, you need to write all the items (rows) You want to buy on the list (document fragments), and then purchase all the items in the supermarket, instead of going to the same thing once
Var frag = document. createDocumentFragment ();
For (var I = 0; I <MyArr. length; I ++ ){
Frag. appendChild (MyArr [I]); // Add all rows in the array to the file fragment.
}
DBody. appendChild (frag); // Add all rows in the File Fragment to the body.

In this way, you can complete a sorting. There is a CustomCompare function, which is a custom sorting method used as a parameter of the Sort method. It has two parameters, one of which is a sorting column, one is the data type.
Function body:
Copy codeThe Code is 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, the form that can be written is thanks to the closure. In the sort method, traverse each item in the array (each item stores every row of table), pass the parameter to CompareTRs (TR1, TR2), and return the result.
In fact, this is OK, but what if you want to sort images?
What is the image type? I don't know. We can use the title of the image or the alt attribute. They can always be strings. Give them a custom attribute customvalue, and then sort its values. Only in implementation
To determine whether this attribute exists, you must modify the CompareTRs method.
Copy codeThe Code is as follows:
Function CustomCompare (Col, DataType ){
Return function CompareTRs (TR1, TR2 ){
Var value1, value2;
// Determine whether the customvalue attribute exists.
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;
};
}

Sorting images is also solved. What if the user needs to be sorted multiple times? Do we need to modify the CompareTRs method?
Obviously, this is not necessary. In JavaScript, there is a reverse () method that can reverse each item in the array. This is the only way to modify the SortTable method.
Copy codeThe Code is 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];
}
// Determine whether the last sorted column is the same as the current column
If (DBody. CurrentCol = Col ){
MyArr. reverse (); // invert the Array
}
Else {
MyArr. sort (CustomCompare (Col, DataType ));
}
// Create a File Fragment and add all rows to it. This is equivalent to a temporary storage shelf. The purpose is (if it is directly added to the document. in the body, a row is inserted and refreshed once. If there is more data, the user experience will be affected)
// First place all rows in the storage shelf, and then add the rows in the storage shelf together to document. body, so that the table will be refreshed only once.
// Just like when you go to the store for shopping, you need to write all the items (rows) You want to buy on the list (document fragments), and then purchase all the items in the supermarket, instead of going to the same thing once
Var frag = document. createDocumentFragment ();
For (var I = 0; I <MyArr. length; I ++ ){
Frag. appendChild (MyArr [I]); // Add all rows in the array to the file fragment.
}
DBody. appendChild (frag); // Add all rows in the File Fragment to the body.
DBody. CurrentCol = Col; // record the column currently sorted
}

JavaScript must be case sensitive and error-prone.
The code above is tested successfully, sorting the date and effect

All code:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> table sorting </title>
<Script type = "text/javascript">
Var IsAsc = true;
Function SortTable (TableID, Col, DataType ){
Var imgSort = document. getElementById ('col' + col );
// Determine whether it is in reverse order 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];
}
// Determine whether the last sorted column is the same as the current column
If (DBody. CurrentCol = Col ){
MyArr. reverse (); // invert the Array
}
Else {
MyArr. sort (CustomCompare (Col, DataType ));
}
// Create a File Fragment and add all rows to it. This is equivalent to a temporary storage shelf. The purpose is (if it is directly added to the document. in the body, a row is inserted and refreshed once. If there is more data, the user experience will be affected)
// First place all rows in the storage shelf, and then add the rows in the storage shelf together to document. body, so that the table will be refreshed only once.
// Just like when you go to the store for shopping, you need to write all the items (rows) You want to buy on the list (document fragments), and then purchase all the items in the supermarket, instead of going to the same thing once
Var frag = document. createDocumentFragment ();
For (var I = 0; I <MyArr. length; I ++ ){
Frag. appendChild (MyArr [I]); // Add all rows in the array to the file fragment.
}
DBody. appendChild (frag); // Add all rows in the File Fragment to the body.
DBody. CurrentCol = Col; // record the column currently sorted
}
Function CustomCompare (Col, DataType ){
Return function CompareTRs (TR1, TR2 ){
Var value1, value2;
// Determine whether the customvalue attribute exists.
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>
</Head>
<Body>
<Div id = "container">
<Table border = "1" id = "MyTable">
<Thead>
<Tr>
<Td onclick = "SortTable ('mytable', 0, 'string')" style = "cursor: pointer "> image sorting </td>
<Td onclick = "SortTable ('mytable', 1, 'int')" style = "cursor: pointer "> integer sorting </td>
<Td onclick = "SortTable ('mytable', 2, 'float')" style = "cursor: pointer "> floating point sorting </td>
<Td onclick = "SortTable ('mytable', 3, 'string')" style = "cursor: pointer "> string sorting </td>
<Td onclick = "SortTable ('mytable', 4, 'date')" style = "cursor: pointer "> date sorting </td>
</Tr>
</Thead>
<Tbody>
<Tr>
<Td customvalue = "doc">
</td>
<Td> 2 </td>
<Td> 5.4 </td>
<Td> zd </td>
<Td> 14:33:13 </td>
</Tr>
<Tr>
<Td customvalue = "zip">
</td>
<Td> 267 </td>
<Td> 8.9 </td>
<Td> xx </td>
<Td> 14:36:13 </td>
</Tr>
<Tr>
<Td customvalue = "xlt">
</td>
<Td> 6 </td>
<Td> 60.4 </td>
<Td> ty </td>
<Td> 19:33:13 </td>
</Tr>
<Tr>
<Td customvalue = "txt">
</td>
<Td> 9 </td>
<Td> 0.8 </td>
<Td> lp; </td>
<Td> 14:33:13 </td>
</Tr>
<Tr>
<Td customvalue = "doc">
</td>
<Td> 34 </td>
<Td> 9.4 </td>
<Td> cv </td>
<Td> 1009-10-31 14:33:13 </td>
</Tr>
<Tr>
<Td customvalue = "txt">
</td>
<Td> 289 </td>
<Td> 23.4 </td>
<Td> uio </td>
<Td> 14:33:13 </td>
</Tr>
<Tr>
<Td customvalue = "zip">
</td>
<Td> 45 </td>
<Td> 89.4 </td>
<Td> cb </td>
<Td> 1039-10-31 14:33:13 </td>
</Tr>
<Tr>
<Td customvalue = "doc">
</td>
<Td> 2 </td>
<Td> 5.4 </td>
<Td> zd </td>
<Td> 14:33:13 </td>
</Tr>
<Tr>
<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>
</Html>

Related Article

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.