我有这段代码link:
function sortTable(table, col, reverse) {
var tb = table.tBodies[0],
tr = Array.prototype.slice.call(tb.rows, 0),
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) {
return reverse
* (a.cells[col].textContent.trim()
.localeCompare(b.cells[col].textContent.trim(), undefined, {numeric: true})
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]);
}
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return;
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
window.onload = function () {makeAllSortable();};
这是对表中的记录进行排序的代码,但是当我在表中时,负数排序无法正常工作。例如,我有数字:-132
,-11232
,0.24
,0.432
,2423432
脚本按顺序排序desc
:2423432
,0.432
,0.24
,-11232
,-132
或asc
:-132
,-11232
,0.24
,0.432
,2423432
。
但它应该是正确的-11232
,-132
,0.24
,0.432
,2423432
演示:jsfiddle
答案 0 :(得分:0)
您正在排序字符串类型的值。使用parseFloat()转换为数字。