Jak sortować tabelę

Naucz się, jak używać JavaScript do sortowania tabel HTML.

Kliknij przycisk, aby posortować tabelę według nazw klientów w porządku alfabetycznym:

Name Country
Berglunds snabbkop Sweden
North/South UK
Alfreds Futterkiste Germany
Koniglich Essen Germany
Magazzini Alimentari Riuniti Italy
Paris specialties France
Island Trading UK
Śmiech Baczusa Winne cellars Canada

Spróbuj sam

Utwórz funkcję sortującą

przykład

function sortTable() {
  var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("myTable");
  switching = true;
  /* Make a loop until the condition is met. */
  no switching has been done: */
  while (switching) {
    // Najpierw zadeklaruj: bieżąca linia nie wymaga wymiany:
    switching = false;
    rows = table.rows;
    /* Traverse all table rows (except the first one, which contains the header): */
    dla (i = 1; i < (rows.length - 1); i++) {
      // First declare that no exchanges should be made:
      shouldSwitch = false;
      /* Get the two elements to be compared, 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 positions:
      jeśli (dir == "desc") {
        // If an exchange should be made, mark it as needing an exchange and exit the current loop
        shouldSwitch = true;
        break;
      }
    }
    jeśli (shouldSwitch) {
      /* Jeśli oznaczono wymianę, wykonaj wymianę i oznacz jako dokonaną wymianę: */
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
    }
  }
}

Spróbuj sam

Sort the table by clicking on the table header

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

The first click will sort in ascending order (from A to Z).

Click 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 specialties France
Island Trading UK
Śmiech Baczusa Winne cellars Canada

przykład

<table id="myTable2">
<tr>
<!--When the table header is clicked, run the sortTable function and pass a parameter, 0 for sorting by name, 1 for sorting 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;
  // Ustaw kierunek sortowania na rosnący:
  dir = "asc";
  /* Utwórz pętlę, która będzie trwać, aż nie będzie już żadnych wierszy do wymiany: */
  while (switching) {
    // Najpierw zadeklaruj: bieżąca linia nie wymaga wymiany:
    switching = false;
    rows = table.rows;
    /* Przejdź przez wszystkie wiersze tabeli (z wyjątkiem pierwszego, ponieważ zawiera nagłówek tabeli): */
    dla (i = 1; i < (rows.length - 1); i++) {
      // Najpierw zadeklaruj: bieżąca linia i linia poniżej nie powinny być wymienione miejscami:
      shouldSwitch = false;
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      /* Sprawdź, czy te dwie linie powinny być wymienione miejscami, opierając się na kierunku sortowania, rosnącym lub malejącym: */
      jeśli (dir == "asc") {
      jeśli (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        jeśli (dir == "desc") {
          // Jeśli należy wymienić, oznacz jako wymagającą wymiany i wyjdź z bieżącej pętli:
          shouldSwitch = true;
          break;
        }
      }
        jeśli (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          // Jeśli należy wymienić, oznacz jako wymagającą wymiany i wyjdź z bieżącej pętli:
          shouldSwitch = true;
          break;
        }
      }
    }
    jeśli (shouldSwitch) {
      /* Jeśli oznaczono wymianę, wykonaj wymianę i oznacz jako dokonaną wymianę: */
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      // Każdy raz, gdy dokonano wymiany, ten licznik zwiększa się o 1:
      switchcount++;
    }
      /* Jeśli nie dokonano wymiany i kierunek sortowania jest "rosnący", ustaw kierunek sortowania na "malejący" i uruchom pętlę while ponownie. */
      jeśli (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}
</script>

Spróbuj sam

sortowanie tabeli według liczby

przykład

jeśli (Number(x.innerHTML) > Number(y.innerHTML)) {
  shouldSwitch = true;
  break;
}

Spróbuj sam