JQuery сортировка таблицы без плагина - PullRequest
3 голосов
/ 20 марта 2009

Есть ли функция jquery для сортировки таблицы. Мне известен плагин JQuery Tablesorter, но я хочу по возможности избегать его использования.

Как FYI - таблица, в которой у меня есть заголовок с пользовательскими изображениями для обозначения возрастающей и убывающей. Тип данных может быть практически любого типа.

РЕДАКТИРОВАТЬ: Могу ли я сделать сортировку таблицы в Javascript?

Ответы [ 5 ]

9 голосов
/ 29 августа 2013

Это очень возможно. Вы можете сделать это так

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

Взгляните на эту Скрипку

(Я не являюсь автором кода выше или той скрипки, я просто нашел его во время поиска решения.)

2 голосов
/ 20 марта 2009

У гуру Javascript Стюарта Лэнгриджа есть хорошая альтернатива использованию jQuery, которая называется tablesorter.js

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

Я использовал это раньше; отлично работает и довольно легкий.

1 голос
/ 03 июня 2014

Мне пришлось немного изменить функцию сортировки, чтобы она игнорировала нечисловые символы, надеюсь, это сэкономит кому-то время ....

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 голосов
/ 29 сентября 2018

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;
    }   
  }   
}
0 голосов
/ 09 июня 2015

Для маленьких столов я делаю это так ...

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

... которые будут сортировать строки, имеющие класс «data_row», внутри таблицы с именем «sample table» на основе ячеек в первом столбце (т. Е. Индекс столбца 0) в порядке возрастания.

Для больших таблиц и дополнительных функций я использую ...

Справа, я нахожу, что DataTables намного проще в использовании, чем TableSorter (например, нет необходимости ссылаться или добавлять дополнительные CSS и графические объекты, если вы не хотите), и документация превосходна. Мне также нравится функциональность по умолчанию (например, функция поиска).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...