我有一段代码用于对HTML表中的列进行排序,它的工作原理非常完美......除了日期字段。字母和纯数字它很好用!但是在日期列上使用时,分拣机不能按我的要求工作。目前日期排序得到像这样:没有插件的JavaScript排序日期
2016年1月2日
2016年2月1日
二○一四年十二月一十二日
2015年12月14日
我想要发生的事情是:
2014年12月12日
2015年12月14日
2016年1月2日
2016年2月1日
这里是JavaScript,我使用,使这种目前的工作:
var tb, asc1 = 1,
asc2 = 1,
asc3 = 1,
asc4 = 1,
asc5 = 1,
asc6 = 1;
function sort_table(tbody, col, asc) {
var rows = tbody.rows,
rlen = rows.length,
arr = new Array(),
i, j, cells, clen;
// fill the array with values from the table
for (i = 0; i < rlen; i++) {
cells = rows[i].cells;
clen = cells.length;
arr[i] = new Array();
for (j = 0; j < clen; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
// sort the array by the specified column number (col) and order (asc)
arr.sort(function (a, b) {
return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1 * asc);
});
// replace existing rows with new rows created from the sorted array
for (i = 0; i < rlen; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
}
的onclick功能是这样的:
function test() {
sort_table(tb, 0, asc1); asc1 *= -1; asc2 = 1; asc3 = 1; asc4 = 1; asc5 = 1; asc6 = 1;
};
有没有人有任何建议我可以做到这一点!我对Javascript真的很陌生,每天仍在学习!日期格式为mm-dd-yyyy,如果您无法从我的示例中知道。任何帮助将不胜感激!
UPDATE
我所采用丹尼尔·阿尔梅达代码,因为他有它在示例工作正是我想要它,但我无法将自己的代码中包含它。当我这样做的时候,似乎是不稳定的,到处都是。我现在用下面的代码工作:
var sorter = function(id, column, order, isDate) {
var t = document.getElementById(id);
var rows = Array.prototype.slice.call(t.rows, 0);
rows = rows.sort(function(a, b) {
var dtA = (isDate) ? new Date(a.cells[column].innerHTML) : a.cells[column].innerHTML;
var dtB = (isDate) ? new Date(b.cells[column].innerHTML) : b.cells[column].innerHTML;
return (order == 0) ? dtA > dtB : dtA < dtB;
});
for (i = 0; i < rows.length; i++) {
t.appendChild(rows[i]);
}
}
我还创建了一个的jsfiddle但我不能得到的jsfiddle做任何事情。担心我错过了一些我不知道的东西。这里是jsfiddle。
拆分两个表的原因是底部表是动态加载的,当有100个返回记录时,容器div允许使用滚动窗口而不是长长的信息列表。
商店的实际日期的对象和排序的,而不是排序的字符串。只需要将日期对象转换为需要显示的字符串。 – forgivenson