迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 排序 HTML 表格

作者:迹忆客 最近更新:2024/03/19 浏览次数:

我们经常遇到希望使表格具有交互性的情况。我们可能只想通过单击列或任何其他方法来对它们进行排序。HTML 没有任何编程能力,因此我们必须使用 JavaScript 对 HTML 表进行排序。不幸的是,没有内置的方法可以帮助我们对数组进行排序。因此,我们编写了利用 DOM 操作功能和比较功能的自定义方法。本教程教授如何使用 JavaScript 对 HTML 表进行排序。


使用 JavaScript 对 HTML 表格进行排序

用户定义的方法使用以下两个辅助函数对数组进行排序。

  • getCellValue()

一个函数,用于从给定表格行和列索引的单元格中获取内容。

我们使用表格行的 children 属性通过 tr.children[i] 选择第 i 列,然后使用其 innerTexttextContent 属性来获取存储的实际内容。一旦我们获得了单元格中的实际内容,我们就可以使用自定义比较器对这些值进行比较和排序。

  • comparer()

用于比较给定表中两个元素的值的函数。

我们首先使用具有指定行和列索引的 getCellValue() 函数获取单元格的内容。然后我们检查两者是否都是有效的整数或字符串,然后比较它们以找到正确的顺序。

算法

  • 通过向表中添加事件侦听器来使表中的所有标题都可点击。
  • 查找所选列中除第一行之外的所有行。
  • 使用 JavaScript 的 sort() 函数和 comparer() 对元素进行排序。
  • 将排序后的行插入回表中以获取最终排序表作为输出。

代码

const getCellValue = (tableRow, columnIndex) =>
    tableRow.children[columnIndex].innerText ||
    tableRow.children[columnIndex].textContent;

const comparer = (idx, asc) => (r1, r2) =>
    ((el1, el2) => el1 !== '' && el2 !== '' && !isNaN(el1) && !isNaN(el2) ?
         el1 - el2 :
         el1.toString().localeCompare(el2))(
        getCellValue(asc ? r1 : r2, idx), getCellValue(asc ? r2 : r1, idx));

// do the work...
document.querySelectorAll('th').forEach(
    th => th.addEventListener(
        'click', (() => {
          const table = th.closest('table');
          Array.from(table.querySelectorAll('tr:nth-child(n+2)'))
              .sort(comparer(
                  Array.from(th.parentNode.children).indexOf(th),
                  this.asc = !this.asc))
              .forEach(tr => table.appendChild(tr));
        })));

所有主要浏览器都支持上面讨论的所有方法。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便