gpt4 book ai didi

javascript - 对包含空单元格的表格进行排序

转载 作者:行者123 更新时间:2023-12-02 23:14:58 25 4
gpt4 key购买 nike

我希望如何使空单元格在升序顺序期间位于顶部,在降序顺序期间位于底部。这是我的代码

function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("mytable");
switching = true;

dir = "asc";

while (switching) {
//start by saying: no switching is done:
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;
}
}
}
}

我遵循了该网站的教程

https://www.w3schools.com/howto/howto_js_sort_table.asp

但是结果是这样的

如果按升序排列

a
<empty>
<empty>
<empty>
z

如果是降序排列

z
<empty>
<empty>
<empty>
a

最佳答案

只需用此替换此脚本即可。它会对你有用。

您传递参数 x = rows[i].getElementsByTagName("td")[n]; 而不是 x = rows[i].getElementsByTagName("td") [0];

这就是为什么 HTMl domElement 找不到该 td 元素。

function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable");

switching = true;

dir = "asc";

while (switching) {
//start by saying: no switching is done:
switching = false;
rows = table.rows;

for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("td")[0];
y = rows[i + 1].getElementsByTagName("td")[0];

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;
}
}
}
}

关于javascript - 对包含空单元格的表格进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57203927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com