我尝试对表中的余额进行升序和降序排序,但不能。我查看了 w3schools 教程和 stackoverflow 中关于 insertBefore 和 insertAfter 的主题(没有库)。但行不通。
我的代码:
function sortTableByBalance() {
let table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("myTable");
switching = true;
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < rows.length - 1; i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[2];
y = rows[i + 1].getElementsByTagName("TD")[2];
if (Number(x.innerHTML) > Number(y.innerHTML)) {
shouldSwitch = true;
break;
} else if (Number(x.innerHTML) < Number(y.innerHTML)) {
shouldSwitch = false;
break;
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
else if (!shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i].nextSibling);
switching = true;
}
}
}
shouldSwitch
设置为
false
时退出内部循环,该算法未正确实现:它不会检测到下一对的顺序不正确。 所以快速解决方法就是改变这一点:
} else if (Number(x.innerHTML) < Number(y.innerHTML)) {
shouldSwitch = false;
break;
对此:
} else if (Number(x.innerHTML) < Number(y.innerHTML)) {
shouldSwitch = false;
更好的方法
sort
,您也可以依靠它来进行此表格排序:
function sortTableByBalance() {
const table = document.getElementById("myTable");
const arr = Array.from(table.rows, row => [row, +row.cells[2].textContent]).slice(1);
arr.sort(([,a], [,b]) => a - b);
for (const [elem] of arr) {
table.appendChild(elem);
}
}