• 在h5中使用 JavaScript 和 HTML DOM 对表格的表头进行排序的解决方案


    在 HTML5 (h5) 中,可以使用 JavaScript 和 HTML DOM 来对表格的表头进行排序。以下是一个简单的示例,使用纯 JavaScript 实现:

    1. 首先,在 HTML 中创建一个带有表头的表格:
    <table id="myTable">
      <thead>
        <tr>
          <th onclick="sortTable(0)">Nameth>
          <th onclick="sortTable(1)">Ageth>
          <th onclick="sortTable(2)">Emailth>
        tr>
      thead>
      <tbody>
        <tr>
          <td>John Doetd>
          <td>30td>
          <td>john.doe@example.comtd>
        tr>
        
      tbody>
    table>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    1. 然后,使用 JavaScript 来实现排序功能:
    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;
          }
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    这个示例中的 sortTable 函数接受一个参数(表头的索引),然后按照该索引对应的列进行排序。排序是按照字母顺序进行的,你可以根据需要调整比较的逻辑。此外,在每次交换元素后,会记录交换的次数,如果连续交换的次数为0,则尝试反转排序方向。这可以防止在数据已经是降序排列的情况下无法进行排序的问题。


    @漏刻有时

  • 相关阅读:
    5、Mybatis的查询功能(必定有返回值)
    《在线编程-Python篇》Python入门 01 输入输出
    wordpress搭建自己的博客详细过程以及踩坑
    系统架构师案例分析(真题知识点整理、记忆)
    OkHttp原理 一篇文章就够了
    工地反光衣识别检测系统
    MIT_线性代数笔记:列空间和零空间
    大模型chatgpt4分析功能初探
    算法:(五)哈希表
    攻防世界----easytornado笔记
  • 原文地址:https://blog.csdn.net/weixin_41290949/article/details/132644536