排序使用JavaScript的HTML表格,代码如下 -
<!DOCTYPE html> <html> <head> <title>Sort a HTML Table Alphabetically</title> <style> button { padding: 10px; margin-bottom: 5px; font-size: 16px; font-weight: bold; } body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } table { border-spacing: 0; width: 100%; border: 1px solid #ddd; } th, td { border-top: 1px solid black; text-align: left; padding: 16px; } </style> </head> <body> <h1>Sorting table example</h1> <button onclick="sortTable()">Sort</button> <table class="filterTable"> <tr> <th>Name</th> <th>BirthDay Month</th> </tr> <tr> <td>Ron</td> <td>January</td> </tr> <tr> <td>Shawn</td> <td>April</td> <tr> <tr> <td>Caleb</td> <td>December</td> </tr> <tr> <td>Bruno</td> <td>February</td> </tr> <tr> <td>Jack</td> <td>October</td> </tr> <tr> <td>Max</td> <td>November</td> </tr> </table> <script> function sortTable() { var filterTable, rows, sorted, i, x, y, sortFlag; filterTable = document.querySelector(".filterTable"); sorted = true; while (sorted) { sorted = false; rows = filterTable.rows; for (i = 1; i < rows.length - 1; i++) { sortFlag = false; x = rows[i].getElementsByTagName("TD")[0]; y = rows[i + 1].getElementsByTagName("TD")[0]; if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) { sortFlag = true; break; } } if (sortFlag) { rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); sorted = true; } } } </script> </body> </html>
输出结果
上面的代码将产生以下输出 -
在点击排序按钮-