The example in this article describes how to implement Table sorting in JavaScript. Share it with everyone for your reference. The specific implementation method 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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>表格排序</title> <style type="text/css"> body { margin:0; padding:0; font-size:14px; } table,td,th { border:1px solid red; } th { width:100px; background:pink; } table { margin:0 auto; } a { text-decoration:none; } </style> <script type="text/javascript"> function sortAge() { //获得表格对象 var tblObj = document.getElementById("tblData"); //把行节点集合存放到临时数组中, //注意这里存放的是表格行节点对象集合的引用 //后续把排序后的数据添加回表格时,不需要删除行节点。 var rowNodes = tblObj.rows; var arrTemp = new Array(); for (var i = 1; i < rowNodes.length; i++) { arrTemp[i - 1] = rowNodes[i]; } var sortFlag = tblObj.rows[0].cells[1].innerText; sortFlag = sortFlag.charAt(sortFlag.length - 1); //取最后一个字符(↑表示升序,↓表示降序) if (sortFlag == "↑") { tblObj.rows[0].cells[1].innerHTML = "<a href='javascript:void(0)' onclick='sortAge()'>年龄↓</a>"; for (var i = 0; i < arrTemp.length; i++) { for (var j = i + 1; j < arrTemp.length; j++) { if (parseInt(arrTemp[j].cells[1].innerText) < parseInt(arrTemp[i].cells[1].innerText)) { var temp = arrTemp[i]; arrTemp[i] = arrTemp[j]; arrTemp[j] = temp; } } } } else { tblObj.rows[0].cells[1].innerHTML = "<a href='javascript:void(0)' onclick='sortAge()'>年龄↑</a>"; for (var i = 0; i < arrTemp.length; i++) { for (var j = i + 1; j < arrTemp.length; j++) { if (parseInt(arrTemp[j].cells[1].innerText) > parseInt(arrTemp[i].cells[1].innerText)) { var temp = arrTemp[i]; arrTemp[i] = arrTemp[j]; arrTemp[j] = temp; } } } } //把排序后的数据添加回表格, //注意由于存放的是引用,所以不需要删除原来的行 var TBodyObj = tblObj.childNodes[0]; for (var i = 0; i < arrTemp.length; i++) { TBodyObj.appendChild(arrTemp[i]); } } </script> </head> <body> <table id="tblData" cellspacing="0px" cellpadding="5px"> <tr> <th>姓名</th> <th><a href="javascript:void(0)" onclick="sortAge()">年龄↑</a></th> <th>城市</th> </tr> <tr> <td>张三</td> <td>25</td> <td>北京</td> </tr> <tr> <td>李四</td> <td>30</td> <td>南昌</td> </tr> <tr> <td>王五</td> <td>21</td> <td>郑州</td> </tr> <tr> <td>李莫</td> <td>35</td> <td>天津</td> </tr> <tr> <td>肖丽</td> <td>19</td> <td>深圳</td> </tr> <tr> <td>罗成</td> <td>23</td> <td>上海</td> </tr> </table> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.