728x90
반응형
표 정렬하기 (정렬, 역정렬)
HTML
<table id="myTable">
<thead>
<tr>
<th onclick="sortTable(0)">번호</th>
<th onclick="sortTable(1)">한글</th>
<th onclick="sortTable(2)">영어</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>나</td>
<td>C</td>
</tr>
<tr>
<td>2</td>
<td>다</td>
<td>A</td>
</tr>
<tr>
<td>3</td>
<td>가</td>
<td>B</td>
</tr>
</tbody>
</table>
java script
<script>
function sortTable(n) {
const table = document.getElementById("myTable");
const tbody = table.querySelector("tbody");
const rows = Array.from(tbody.querySelectorAll("tr"));
rows.sort((rowA, rowB) => {
const cellA = rowA.querySelectorAll("td")[n].textContent;
const cellB = rowB.querySelectorAll("td")[n].textContent;
return cellA.localeCompare(cellB, undefined, {numeric: true, sensitivity: 'base'});
});
if (table.getAttribute("data-sort-dir") === "asc") {
rows.reverse();
table.setAttribute("data-sort-dir", "desc");
} else {
table.setAttribute("data-sort-dir", "asc");
}
table.removeChild(tbody);
rows.forEach(row => tbody.appendChild(row));
table.appendChild(tbody);
}
</script>
728x90
반응형