Как сортировать таблицу

Узнайте, как использовать JavaScript для сортировки таблиц HTML.

Нажмите кнопку, чтобы отсортировать таблицу по алфавиту по имени клиента:

Name Country
Berglunds snabbkop Sweden
North/South UK
Alfreds Futterkiste Germany
Koniglich Essen Germany
Magazzini Alimentari Riuniti Italy
Paris specialites France
Island Trading UK
Laughing Bacchus Winecellars Canada

Попробуйте сами

Создание функции сортировки

пример

function sortTable() {
  var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("myTable");
  switching = true;
  /* Create a loop until the condition is met. */
  no switching has been done: */
  while (switching) {
    // Сначала声明: в настоящее время нет строк, которые нужно обменять:
    switching = false;
    rows = table.rows;
    /* Traverse all table rows (except the first row, which contains the header): */
    for (i = 1; i < (rows.length - 1); i++) {
      // First declare that no swaps should be made:
      shouldSwitch = false;
      /* Get the two elements to compare, one from the current row and one from the next row: */
      x = rows[i].getElementsByTagName("TD")[0];
      y = rows[i + 1].getElementsByTagName("TD")[0];
      // Check if the two rows should be swapped:
      if (dir == "desc") {
        // If the rows should be swapped, mark them as needing to be swapped and exit the current loop
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /* Если строка помечена как нуждающаяся в обмене, выполните обмен и пометьте как выполненный: */
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
    }
  }
}

Попробуйте сами

Sort the table by clicking on the table header

Click "Name" to sort by name, click "Country" to sort by country.

The sorting order is ascending (from A to Z) when clicked for the first time.

When clicked again, the sorting order will be descending (from Z to A):

Name Country
Berglunds snabbkop Sweden
North/South UK
Alfreds Futterkiste Germany
Koniglich Essen Germany
Magazzini Alimentari Riuniti Italy
Paris specialites France
Island Trading UK
Laughing Bacchus Winecellars Canada

пример

<table id="myTable2">
<tr>
<!--When the table header is clicked, run the sortTable function and pass a parameter, 0 means sort by name, 1 means sort by country: -->
<th onclick="sortTable(0)">Name</th>
<th onclick="sortTable(1)">Country</th>
</tr>
...
<script>
function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("myTable2");
  switching = true;
  // Установите направление сортировки на возрастание:
  dir = "asc";
  /* Создайте цикл, который будет продолжаться до тех пор, пока не останется строк, которые нужно обменять: */
  while (switching) {
    // Сначала声明: в настоящее время нет строк, которые нужно обменять:
    switching = false;
    rows = table.rows;
    /* Пробегитесь по всем строкам таблицы (кроме первой, так как она содержит заголовки): */
    for (i = 1; i < (rows.length - 1); i++) {
      // Сначала声明:текущая строка и следующая строка не должны меняться местами:
      shouldSwitch = false;
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      /* Проверьте, должны ли эти строки меняться местами, основываясь на направлении сортировки, возрастанию или убыванию: */
      if (dir == "asc") {
      if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        if (dir == "desc") {
          // Если нужно выполнить обмен, пометьте как нуждающийся в обмене и выйдите из текущего цикла:
          shouldSwitch = true;
          break;
        }
      }
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          // Если нужно выполнить обмен, пометьте как нуждающийся в обмене и выйдите из текущего цикла:
          shouldSwitch = true;
          break;
        }
      }
    }
    if (shouldSwitch) {
      /* Если строка помечена как нуждающаяся в обмене, выполните обмен и пометьте как выполненный: */
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      // Этот счетчик увеличивается на 1 каждый раз, когда выполняется обмен:
      switchcount ++;
    }
      /* Если не было выполнено обменов и направление сортировки равно "возрастанию", то установите направление сортировки на "убывание" и повторно выполните цикл while. */
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}
</script>

Попробуйте сами

сортировка таблицы по числовому значению

пример

if (Number(x.innerHTML) > Number(y.innerHTML)) {
  shouldSwitch = true;
  break;
}

Попробуйте сами