【发布时间】:2016-11-29 14:20:06
【问题描述】:
使用以下 jQuery 代码对表格行进行排序,千位格式的带有点的数字排序不正确:
这些数字:
1.000、2.500、4.000、850
排序为:
850、4.000、2.500、1.000
我需要订购这些样品编号而不删除点。
jQuery 代码:
$('th').each(function (column) {
$(this).addClass('sortable').click(function () {
var findSortKey = function ($cell) {
return $cell.find('.sort-key').text().toUpperCase()+ ' ' + $cell.text().toUpperCase();
};
var sortDirection = $(this).is('.sorted-asc') ? -1 : 1;
var $rows = $(this).parent().parent().parent().find('tbody tr').get();
var bob = 0;
// Loop through all records and find
$.each($rows, function (index, row) {
row.sortKey = findSortKey($(row).children('td').eq(column));
});
// Compare and sort the rows alphabetically or numerically
$rows.sort(function (a, b) {
if (a.sortKey.indexOf('-') == -1 && (!isNaN(a.sortKey) && !isNaN(a.sortKey))) {
// Rough Numeracy check
if (parseInt(a.sortKey) < parseInt(b.sortKey)) {
return -sortDirection;
}
if (parseInt(a.sortKey) > parseInt(b.sortKey)) {
return sortDirection;
}
} else {
if (a.sortKey < b.sortKey) {
return -sortDirection;
}
if (a.sortKey > b.sortKey) {
return sortDirection;
}
}
return 0;
});
// Add the rows in the correct order to the bottom of the table
$.each($rows, function (index, row) {
$('tbody').append(row);
row.sortKey = null;
});
// Identify the column sort order
$('th').removeClass('sorted-asc sorted-desc');
var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')');
sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');
// Identify the column to be sorted by
$('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
});
});
【问题讨论】:
-
这就是为什么您从不对格式化或本地化的日期、数字等进行排序。
-
显然
1.000小于850。 -
@PraveenKumar 您标记为重复的问题是关于数据表的。这是一个自定义函数,而不是插件。该解决方案不符合我的要求。
-
@user3472675 重新打开。
-
没有接受的答案,但看看这个相关/重复的问题:stackoverflow.com/questions/25645163/…
标签: jquery