【发布时间】:2020-01-15 12:15:37
【问题描述】:
我有一张表,我想对日期列进行升序和降序排序。
我已经尝试了下面的代码,但它不起作用。它仅在对数字进行排序时起作用。
function sortColumn() {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("example");
switching = true;
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[6];
y = rows[i + 1].getElementsByTagName("TD")[6];
if (parseInt(x.innerHTML.toLowerCase()) > parseInt(y.innerHTML.toLowerCase())) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
【问题讨论】:
-
这里有很多值得挑选的地方。首先,
parseInt()将接受一个字符串,如"2",并返回整数2。但它不会处理像"13/09/2018"这样的字符串,因为它不仅仅是数字字符。工作量更大,但您可以考虑将表数据收集到对象数组中,然后使用排序工具确定排序顺序,然后将数据放回新顺序。
标签: javascript jquery html html-table