实现html表的数值排序

Implement numerical sorting for html table?

本文关键字:排序 html 实现      更新时间:2023-09-26

谁能帮我修改这个代码,以支持数值排序。目前它只支持按字母顺序排序,我自己不是一个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())
               );
https://jsfiddle.net/oqr0mjc6/3/

您应该将比较代码更改为

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;
       }
    }
}

更简单的标准,如"如果它们都是数字,将它们作为数字进行比较,否则将它们作为字符串进行比较",就不能很好地工作了,因为

  • "2"& lt;"10"
  • "10"& lt;"10"
  • "10"& lt;"2"

。您可以创建逻辑"循环",对于这些循环,排序的概念是没有意义的。

在您的排序函数中,您可以尝试将a.cells[col].textContent.trim()转换为数字。如果不是数字,就按词序比较,否则就比较