【发布时间】:2018-09-15 03:45:14
【问题描述】:
下面的 JS 函数仅根据 td 中的第一个数字对 myTable 中的 td:s 进行排序。如何根据 td 中的所有数字对其进行排序(从低到高排序;例如 1、5、15 而不是 1、15、5)?
function sortTable() {
var 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")[0];
y = rows[i + 1].getElementsByTagName("TD")[0];
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
【问题讨论】:
-
排序数字而不是字符串。 IE。
if (+(x.innerHTML) > +(y.innerHTML))... -
您能否更新您的问题并包含您正在使用的表格的示例,您是否尝试过解析数字
int而不是字符串?谢谢。
标签: javascript sorting html-table