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>
출력
위의 코드는 다음 출력을 생성합니다 -
정렬 을 클릭하면 버튼 -