使用jQuery对表格进行排序,无需插件

4
有没有一种jquery函数可以对表格进行排序?我知道JQuery Tablesorter插件,但如果可能的话,我想避免使用它。
顺便说一下 - 我有一个带有自定义图片的标题的表格,用于指示升序和降序。数据类型可以是任何类型。
编辑:我能在Javascript中对表格进行排序吗?

我的解决方案对你有用吗? - Aditya Ponkshe
5个回答

10
这是完全可能的。您可以像这样做:
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();};

请看这个Fiddle示例。

(以上代码和示例不是我编写的,我只是在寻找解决方案时发现了它。)


这个程序本身是完美的,唯一的问题是当列中有数字数据时,它无法正确排序。例如1、1112、2、54、73应该按照1、2、54、73、1112的顺序排序。但是在这里,它将每个数字视为一个字符,然后进行排序。有什么解决办法吗?我已经尝试使用parseInt()转换值,但不起作用。 - sandeep
如果我有多个表格,但只想对其中一个进行排序,怎么办? - highwingers
parent.getElementsByTagName('table')[1] -- 获取第二个表格 - highwingers

2

你的回答没有满足问题要求:不使用插件。 - Redips77

1

https://www.w3schools.com/howto/howto_js_sort_table.asp

function sortTable() {
  var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("myTable");
  switching = true;
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // Start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    /* Loop through all table rows (except the 
    first, which contains table headers): */
    for (i = 1; i < (rows.length - 1); i++) {
      // Start by saying there should be no switching:
      shouldSwitch = false;
      /* Get the two elements you want to compare,
      one from current row and one from the next: */
      x = rows[i].getElementsByTagName("TD")[0];
      y = rows[i + 1].getElementsByTagName("TD")[0];
      // Check if the two rows should switch place:
      if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        // If so, mark as a switch and break the loop:
        shouldSwitch = true;
        break;
      }   
    }   
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark that a switch has been done: */
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
    }   
  }   
}

1

我不得不稍微更改排序函数,这样它就会忽略非数字字符,希望这将为某些人节省时间....

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 * (Number(a.cells[col].textContent.replace(/[^\d.-]/g, ''))
             - Number(b.cells[col].textContent.replace(/[^\d.-]/g, '')));
    });

    for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}

0

对于小表格,我会这样做...

sortTable = function(tableName, rowClass, columnNumber, ascending) {
    var row, cell, cellContent;
    var comparisonRow, comparisonCell, comparisonContent;

    $("#" + tableName + " tr." + rowClass).each(function(i) {
        row = $("#" + tableName + " tr." + rowClass + ":eq(" + i + ")");
        cell = $(row).find("td:eq(" + columnNumber + ")");
        cellContent = $(cell).html();

        $("#" + tableName + " tr." + rowClass).each(function(j) {
            comparisonRow = $("#" + tableName + " tr." + rowClass + ":eq(" + j + ")");
            comparisonCell = $(comparisonRow).find("td:eq(" + columnNumber + ")");
            comparisonContent = $(comparisonCell).html();

            if ( (ascending && cellContent < comparisonContent) || (!ascending && cellContent > comparisonContent) ) {
                $(row).insertBefore(comparisonRow);
                return false;
            }
        });
    });
};

说明:该函数遍历指定表格的每一行(特定类别),记录HTML内容(来自指定列的单元格),然后遍历所有表格行,比较单元格内容(再次来自指定列)。当单元格内容小于或大于(基于“升序”是否设置为true)时,将该行插入到正在进行比较的行前面。

一个示例调用可能是...

sortTable("sample_table", "data_row", 0, true);

...将会根据第一列(即列索引0)中的单元格,以升序排序具有“data_row”类别的行,位于名为“sample table”的表格内。

对于更大的表格和其他功能,我使用...

就我个人而言,我发现DataTables比TableSorter更易于使用(例如,无需引用或合并其他CSS和艺术品,除非您想要),而且文档非常好。我也喜欢其默认功能(例如,其搜索功能)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接