Solution to sorting table headers using JavaScript and HTML DOM in h5

In HTML5 (h5), you can use JavaScript and the HTML DOM to sort table headers. Here's a simple example, implemented in pure JavaScript:

  1. First, create a table with a header in HTML:
<table id="myTable">
  <thead>
    <tr>
      <th onclick="sortTable(0)">Name</th>
      <th onclick="sortTable(1)">Age</th>
      <th onclick="sortTable(2)">Email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Doe</td>
      <td>30</td>
      <td>[email protected]</td>
    </tr>
    <!-- 更多的行... -->
  </tbody>
</table>
  1. Then, use JavaScript to implement the sorting function:
function sortTable(n) {
    
    
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("myTable");
  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()) {
    
    
          shouldSwitch = true;
          break;
        }
      } else if (dir == "desc") {
    
    
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
    
    
          shouldSwitch = true;
          break;
        }
      }
    }
    if (shouldSwitch) {
    
    
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      switchcount ++; // 如果已经进行了多次交换,可以考虑降序或者结束排序操作。这里只是简单地记录交换次数。
    } else {
    
    
      if (switchcount == 0 && dir == "asc") {
    
    
        dir = "desc";
        switching = true;
      }
    }
  }
}

The function in this example sortTabletakes one parameter (the index of the table header) and sorts by the column corresponding to that index. Sorting is done alphabetically, and you can adjust the comparison logic as needed. In addition, after each exchange of elements, the number of exchanges is recorded. If the number of consecutive exchanges is 0, an attempt is made to reverse the sorting direction. This prevents problems when the data is already sorted in descending order.


@missingsometimes

Guess you like

Origin blog.csdn.net/weixin_41290949/article/details/132644536