javascript - 排序表无法正常工作
问题描述
我创建了一个通过单击标题进行排序的表。但是排序效果不好。以图片为例(按升序排序)它是怎样的
我的js代码:
function sortTable(n) {
var table,
rows,
switching,
i,
x,
y,
shouldSwitch,
dir,
switchcount = 0;
table = document.getElementById("myTable");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.getElementsByTagName("TR");
for (i = 1; i < rows.length - 1; i++) { //Change i=0 if you have the header th a separate table.
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;
}}}}
我想你已经知道我的问题了。问:我怎样才能确保它得到正确排序?我真的必须在实际值之前用'0'填充值还是有更好的方法?
解决方案
推荐阅读
- javascript - Javascript拼接与redux一起工作错误
- reactjs - 反应问题。始终检查星级输入
- c++ - 如何将带有特殊字符的 QString 转换为字节流以通过 Linux 管道发送
- mariadb - 多个用户同时访问同一个 Mariadb 数据库
- php - 我网站上的 PHP 计数器坏了
- javascript - 在桌面使用 chrome 移动视图和在移动设备中使用 chrome 的区别
- pine-script - 尝试编写代码,在进行下一次交易之前为策略提供缓冲时间,声明问题
- php - 在 json 数组中搜索函数 SQL
- assembly - 在 x86 程序集中的代码段内定义数据
- r - 如何在保留唯一列的同时重新绑定数据集?