[英]Implement numerical sorting for html table?
有人可以帮我修改此代码以支持数字排序。 目前它只支持按字母顺序排序,我自己不是 js 作家,我在网上找到了这个。 我只需要它对数字进行排序,而不是按字母顺序排序。
奖励:是否可以使其支持数字和字符串
这是按字母顺序排序的工作链接。 jsfiddle.net
谢谢你。
function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
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();};
这适用于字符串和数字
if(!isNaN(a.cells[col].textContent) && !isNaN(b.cells[col].textContent))
return reverse * ((+a.cells[col].textContent) - (+b.cells[col].textContent))
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
您应该将比较代码更改为
return reverse * ((+a.cells[col].textContent) - (+b.cells[col].textContent))
Javascript 中的一元+
可用于将字符串转换为其数值。
对可以同时包含数字和非数字的单列进行排序比较棘手,因为您需要建立一个传递排序标准……例如:
在代码中:
function xcmp(a, b) {
if (isNan(a)) {
if (isNan(b)) {
return a.localeCompare(b);
} else {
return +1; // a non-numeric, b numeric: a > b
}
} else {
if (isNan(b)) {
return -1; // a numeric, b non-numeric: a < b
} else {
return a - b;
}
}
}
更简单的标准,例如“如果两者都是数字,则将它们作为数字进行比较,否则作为字符串比较”效果不佳,因为
即,您可以创建逻辑“循环”,而排序的概念本身没有意义。
在您的排序函数中,您可以尝试将a.cells[col].textContent.trim()
转换为一个数字。 如果它不是数字,则按字典顺序进行比较,否则比较数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.