使用以下jQuery代码来排序表行,带有数千个格式的点的数字未正确排序:
这些数字:
1.000,2.500,4.000,850
按以下顺序排列:
850,4000,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');
});
});
答案 0 :(得分:0)
在JavaScript上,没有数千个分隔符。仅适用于小数及其.
使用点分隔符,您无法将数字变量定义为Int
或float
,因为这将被视为十进制数,并且它会删除十进制后的零。
您仍然可以使用点对数字进行排序。
请尝试:
var numbers = ["4.500", "1.000", "1", "5", "25", "10"];
var num = [];
$.each(numbers,function(i,e){
dotPos = numbers[i].replace(/\./g,"")
num.push(parseInt(dotPos))
})
num.sort(function(a, b){return a-b});
$.each(num,function(i,e){
console.log(num[i].toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1."))
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;