【发布时间】:2019-08-23 01:30:31
【问题描述】:
我的意图是在单击th 时按升序对表格列(仅单击的列)进行排序。在进一步单击时,确切的表格列应按降序排列。
到目前为止我得到了什么:
表格正在排序,但单击时所有三列都在排序 - 我只希望对一列进行排序。
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("table");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount ++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
<table id="table">
<tr>
<th onclick="sortTable(0)">Nummer</th>
<th onclick="sortTable(1)">Land</th>
<th onclick="sortTable(2)">Name</th>
</tr>
<tr>
<td>2</td>
<td>Rumänien</td>
<td>Dan</td>
</tr>
<tr>
<td>1</td>
<td>Deutschland</td>
<td>Aaron</td>
</tr>
<tr>
<td>3</td>
<td>USA</td>
<td>Peter</td>
</tr>
</table>
【问题讨论】:
-
一些改进问题的建议:您应该清楚您期望代码做什么,以及它实际做什么。您还应该解释您认为问题所在以及原因。理想情况下,使示例代码可运行。
-
@AlexMA 我已经更新了帖子,谢谢。
标签: javascript html