【发布时间】:2023-03-24 09:52:01
【问题描述】:
我有来自 w3schools 的以下 Javascript 函数来对列进行排序:
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable");
switching = true;
//Set the sorting direction to ascending:
dir = "asc";
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
rows = table.getElementsByTagName("TR");
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < (rows.length - 1); i++) {
//start by saying there should be no switching:
shouldSwitch = false;
/*Get the two elements you want to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
/*check if the two rows should switch place,
based on the direction, asc or desc:*/
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
//if so, mark as a switch and break the loop:
shouldSwitch= true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
//if so, mark as a switch and break the loop:
shouldSwitch= true;
break;
}
}
}
if (shouldSwitch) {
/*If a switch has been marked, make the switch
and mark that a switch has been done:*/
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
//Each time a switch is done, increase this count by 1:
switchcount ++;
} else {
/*If no switching has been done AND the direction is "asc",
set the direction to "desc" and run the while loop again.*/
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
但是它在我的名为 Internet Explorer 版本的专栏上效果不佳。
它适用于我表的其他列。我不知道为什么会这样。谁能告诉我出了什么问题?
我将这些值复制到 Excel 工作表上并尝试对其进行排序,但排序也不正确。是价值观的问题吗?
它只是考虑数字的第一位然后排序。我该如何解决这个问题?
【问题讨论】:
-
@sauntimo 你能帮忙吗?
-
张贴你的桌子
-
不是图片而是html代码
-
document.write()覆盖所有内容。不要使用它。由于您要将字符串解析为 HTML,请使用innerHTML甚至更好的insertAdjacentHTML() -
欢迎来到 Stack Overflow!请不要破坏您的帖子。提交帖子后,您已将内容许可给整个 Stack Overflow 社区(根据 CC-by-SA 许可)。如果您想取消此帖子与您帐户的关联,请参阅What is the proper route for a disassociation request?
标签: javascript function sorting html-table