下面的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;
}
}
}
发布于 2018-09-15 03:35:46
使用parseInt()
将字符串转换为整数。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
所以,比较应该像这样做-
if (parseInt(x.innerHTML.toLowerCase()) > parseInt(y.innerHTML.toLowerCase())) {
https://stackoverflow.com/questions/52338182
复制相似问题