[英]Issue sorting table by Date in JQuery
I came across this code to sort a table in JQuery and it works fine for sorting strings and numbers, but dates are treated like strings so when sorting 4/4/2015
and 12/12/2015
and 1/1/2015
the result is : 1/1/2015
, 12/12/2015
, 4/42015
. 我在JQuery中遇到了对代码进行排序的代码,它可以很好地用于对字符串和数字进行排序,但是日期被视为字符串,因此在对
4/4/2015
和12/12/2015
和1/1/2015
进行排序时: 1/1/2015
, 12/12/2015
, 4/42015
。 How can I modify this to correctly sort by dates? 如何修改此日期以按日期正确排序?
$('th').click(function () {
var table = $(this).parents('table').eq(0);
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
this.asc = !this.asc;
if (!this.asc) {
rows = rows.reverse();
$(this).find('a').html('▾');
} else {
$(this).find('a').html('▴');
}
for (var i = 0; i < rows.length; i++) {
table.append(rows[i]);
}
});
function comparer(index) {
return function (a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index);
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB);
}
}
function getCellValue(row, index) { return $(row).children('td').eq(index).html(); }
I took @epascarello's advice and changed it into a Date Object
as follows: 我接受了@epascarello的建议,并将其更改为
Date Object
,如下所示:
$('th').click(function () {
var table = $(this).parents('table').eq(0);
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
this.asc = !this.asc;
if (!this.asc) {
rows = rows.reverse();
$(this).find('a').html('▾');
} else {
$(this).find('a').html('▴');
}
for (var i = 0; i < rows.length; i++) {
table.append(rows[i]);
}
});
function comparer(index) {
return function (a, b) {
var valA;
var valB;
if (getCellValue(a, index).indexOf("/") > -1) //comparing dates
{
valA = new Date(getCellValue(a, index)).setHours(0, 0, 0, 0);
valB = new Date(getCellValue(b, index)).setHours(0, 0, 0, 0);
}
else {
valA = getCellValue(a, index);
valB = getCellValue(b, index);
}
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB);
}
}
function getCellValue(row, index) { return $(row).children('td').eq(index).html(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.