当前位置:网站首页>通过单击表头对表进行排序
通过单击表头对表进行排序
2022-07-26 20:31:00 【紫微前端】
假设我们要对下表的任何列进行排序:
<table id="sortMe" class="table">
...
</table>对行进行排序
// Query the table
const table = document.getElementById('sortMe');
// Query the headers
const headers = table.querySelectorAll('th');
// Loop over the headers
[].forEach.call(headers, function (header, index) {
header.addEventListener('click', function () {
// This function will sort the column
sortColumn(index);
});
});sortColumn(index)函数将按给定的列对所有行进行排序index。为此:// Query all rows
const tableBody = table.querySelector('tbody');
const rows = tableBody.querySelectorAll('tr');
const sortColumn = function (index) {
// Clone the rows
const newRows = Array.from(rows);
// Sort rows by the content of cells
newRows.sort(function (rowA, rowB) {
// Get the content of cells
const cellA = rowA.querySelectorAll('td')[index].innerHTML;
const cellB = rowB.querySelectorAll('td')[index].innerHTML;
switch (true) {
case cellA > cellB:
return 1;
case cellA < cellB:
return -1;
case cellA === cellB:
return 0;
}
});
// Remove old rows
[].forEach.call(rows, function (row) {
tableBody.removeChild(row);
});
// Append new row
newRows.forEach(function (newRow) {
tableBody.appendChild(newRow);
});
};sort方法,该方法接受一个函数来比较两个项目。在我们的例子中,列的两个单元格根据其 HTML 内容进行比较: newRows.sort(function(rowA, rowB) {
// Get the content of cells
const cellA = rowA.querySelectorAll('td')[index].innerHTML;
const cellB = rowB.querySelectorAll('td')[index].innerHTML;
...
});支持其他类型
<thead>
<tr>
<th data-type="number">No.</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>例如,编号列将具有一个data-type="number"属性。如果缺少该属性,则单元格的内容类型为字符串。我们需要一个函数将单元格的内容从字符串转换为另一种类型:
// Transform the content of given cell in given column
const transform = function (index, content) {
// Get the data type of column
const type = headers[index].getAttribute('data-type');
switch (type) {
case 'number':
return parseFloat(content);
case 'string':
default:
return content;
}
};number和string列,但您可以自由支持更多类型,例如日期。sortColumn稍微改进一下功能以支持自定义内容类型。我们不比较原始内容,而是比较基于内容类型转换的值:newRows.sort(function (rowA, rowB) {
const cellA = rowA.querySelectorAll('td')[index].innerHTML;
const cellB = rowB.querySelectorAll('td')[index].innerHTML;
// Transform the content of cells
const a = transform(index, cellA);
const b = transform(index, cellB);
// And compare them
switch (true) {
case a > b:
return 1;
case a < b:
return -1;
case a === b:
return 0;
}
});
支持双向
// Track sort directions
const directions = Array.from(headers).map(function (header) {
return '';
});directions是一个数组,其中每个项目可以是asc或desc指示关联列中的排序方向。该sortColumn()函数现在涉及更多逻辑来根据当前方向比较两行:
const sortColumn = function(index) {
// Get the current direction
const direction = directions[index] || 'asc';
// A factor based on the direction
const multiplier = (direction === 'asc') ? 1 : -1;
...
newRows.sort(function(rowA, rowB) {
const cellA = rowA.querySelectorAll('td')[index].innerHTML;
const cellB = rowB.querySelectorAll('td')[index].innerHTML;
const a = transform(index, cellA);
const b = transform(index, cellB);
switch (true) {
case a > b: return 1 * multiplier;
case a < b: return -1 * multiplier;
case a === b: return 0;
}
});
...
// Reverse the direction
directions[index] = direction === 'asc' ? 'desc' : 'asc';
...
};边栏推荐
猜你喜欢

【HarmonyOS议题资料下载】HDD杭州站·线下沙龙专注应用创新 展现鸿蒙生态魅力

What are the characteristics of low code tools? The two development tracks of low code that can be seen by discerning people!

How to use multiple languages in a project?

How to configure the legendary SF lander to automatically read the list without a network

详解西部数据SMR叠瓦式硬盘的190二级编译器(译码表)模块

测试用例千万不能随便,记录由一个测试用例异常引起的思考

Detailed illustration of B-tree and its implementation in C language

Why does it system need observability?

QT Foundation Day 1 (1) QT, GUI (graphical user interface) development
![[JVM series] JVM tuning](/img/6b/f7c402b2ff5fc4f11f9656a7a59873.png)
[JVM series] JVM tuning
随机推荐
HTTP cache browser cache that rabbits can understand
力扣每日一题-第43天-168. Excel表列名称
[hero planet July training leetcode problem solving daily] 26th and check the collection
MySQL -count: the difference between count (1), count (*), and count (column name)
银河证券场内基金低佣金开户靠谱吗,可靠安全吗
一些意想不到的bug记录
About: get the domain controller of the current client login
6种方法帮你搞定SimpleDateFormat类不是线程安全的问题
How to block the legendary GEE engine version? Close player account tutorial through script + engine
Number() VS parseInt()
Monitor MySQL based on MySQL exporter
[download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng
TypeScript中的类型断言
服务器的防护会遇到什么样的安全问题呢?
kubernetes之Deployment
游览器——游览器游览器缓存
Why didn't Tencent create a game like "original God"
【HCIA安全】用户认证
2022开放原子全球开源峰会议程速递 | 7 月 27 日分论坛议程一览
Error in render: “TypeError: data.slice is not a function“