最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery sorting a table without the plugin - Stack Overflow

programmeradmin0浏览0评论

Is there a jquery function to sort a table. I am aware of the JQuery Tablesorter plugin but I want to avoid using it if possible.

As a FYI - The table that I have a header with custom images to indicate ascending and descending. The data type could be pretty much any type.

EDIT:Can I do sorting of a table in Javascript?

Is there a jquery function to sort a table. I am aware of the JQuery Tablesorter plugin but I want to avoid using it if possible.

As a FYI - The table that I have a header with custom images to indicate ascending and descending. The data type could be pretty much any type.

EDIT:Can I do sorting of a table in Javascript?

Share Improve this question edited Mar 20, 2009 at 15:37 DotnetDude asked Mar 20, 2009 at 2:32 DotnetDudeDotnetDude 11.8k36 gold badges103 silver badges159 bronze badges 1
  • my solution worked for you? – Aditya Ponkshe Commented Apr 16, 2014 at 2:48
Add a comment  | 

5 Answers 5

Reset to default 10

It is very much possible. You can do it like this

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

Take a look at this Fiddle

(I am not the author of code above or that fiddle, I just found it while searching for the solution.)

Javascript guru Stuart Langridge has a nice alternative to using jQuery called tablesorter.js

http://www.kryogenix.org/code/browser/sorttable/

I've used it before; works great and it's pretty lightweight.

I had to change the sorting function a little bit so it would ignore non-numeric chars, hopefully this will save somebody some time....

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
}

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

For small tables, I do it this way...

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

Explanation: The function walks through each row (of a specified class) of the specified table, takes note of the HTML content (from the cell of the specified column), and then walks through all of the table's rows comparing the cell content (again from the specified column). When the cell content is less or greater (based on whether "ascending" is set to true), the row is inserted in front of the one to which it was being compared.

A sample call would be...

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

...which would sort rows that have the class "data_row", inside the table named "sample table", based on cells in the first column (i.e, column index 0) in ascending order.

For larger tables and additional features, I use...

  • DataTables

Right of the box, I find DataTables much easier to use than TableSorter (e.g., no need for referencing or incorporating additional CSS and artwork unless you want), and the documentation is excellent. I also like the default functionality (e.g., its Search function).

发布评论

评论列表(0)

  1. 暂无评论