Sort the forms of a small JS demo every day. Key knowledge points: Form operations, node operations, and demodom in DOM
<! DOCTYPE html>
<Html lang = "en">
<Head>
<Meta charset = "UTF-8">
<Title> Document </title>
<Script type = "text/javascript">
Window. onload = function (){
Var input = document. querySelectorAll ('input ');
Var table = document. querySelector ('table ');
Var rows = table. tBodies [0]. rows;
Var arrRows = [];
/* Because only Arrays can be sorted, tr is put into an array */
For (var I = 0; I <rows. length; I ++ ){
ArrRows. push (rows [I]);
}
// ArrRows. sort (function (a, B ){
// Return B. cells [1]. innerHTML-a. cells [1]. innerHTML;
/// Sort by the content of the 1st cells in tr
//});
// ArrRows. forEach (function (tr ){
//// Re-place tr in the tbody according to the order of the number
// Table. tBodies [0]. appendChild (tr );
//});
// Console. log (arrRows );
Input [0]. onclick = function (){
ArrRows. sort (function (a, B ){
Return B. cells [1]. innerHTML-a. cells [1]. innerHTML;
// Sort by the content of the 1st cells in tr
});
ArrRows. forEach (function (tr ){
// Re-place tr into the tbody according to the order of the number
Table. tBodies [0]. appendChild (tr );
});
}
Input [1]. onclick = function (){
ArrRows. sort (function (a, B ){
Return a. cells [1]. innerHTML-B. cells [1]. innerHTML;
// Sort by the content of the 1st cells in tr
});
ArrRows. forEach (function (tr ){
// Re-place tr into the tbody according to the order of the number
Table. tBodies [0]. appendChild (tr );
});
}
};
</Script>
</Head>
<Body>
<Table border = "1" width = "400" align = "center">
<Thead>
<Tr>
<Th> fruit </th>
<Th> unit price (¥) </th>
</Tr>
</Thead>
<Tbody>
<Tr>
<Th> Apple </th>
<Th> 54.5 </th>
</Tr>
<Tr>
<Th> orange </th>
<Th> 24.5 </th>
</Tr>
<Tr>
<Th> watermelon </th>
<Th> 33.8 </th>
</Tr>
<Tr>
<Th> bananas </th>
<Th> 13.8 </th>
</Tr>
</Tbody>
<Tfoot>
<Tr>
<Td colspan = "2" style = "text-align: center;">
<Input type = "button" value = "price from high to low">
<Input type = "button" value = "price from low to high">
</Td>
</Tr>
</Tfoot>
</Table>
</Body>
</Html>