当前位置:网站首页>通过单击表头对表进行排序
通过单击表头对表进行排序
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';
...
};边栏推荐
- 游览器——游览器游览器缓存
- Alkbh1
- 测试用例千万不能随便,记录由一个测试用例异常引起的思考
- JDBC connection
- [must read new] Keya valuation analysis of University of technology, heating energy-saving products
- conda报错:json.decoder.JSONDecodeError:
- JVM学习----内存结构----程序计数器&虚拟机栈&本地方法栈&堆&方法区
- Deployment of kubernetes
- Web3.0 时代,基于P2PDB实现一款Dapp的技术理论
- 6种方法帮你搞定SimpleDateFormat类不是线程安全的问题
猜你喜欢

牛客刷题——Mysql系列

今天公司碰到一个阿里p8,算是真正见识到了基础的天花板
![[Oracle training] - deploy Ogg known as zero downtime migration](/img/bc/4ee0493129d5abab931ca50dbdce6f.png)
[Oracle training] - deploy Ogg known as zero downtime migration

Devops has been practiced for many years. What is the most painful thing?

How to enter the specified user method body when debugging in idea?

Today, the company came across an Alibaba P8, which was really seen as the ceiling of the foundation

Why does it system need observability?
HTTP cache browser cache that rabbits can understand

Flutter性能优化实践 —— UI篇

详解西部数据SMR叠瓦式硬盘的190二级编译器(译码表)模块
随机推荐
[HCIA security] bidirectional nat
Summary of 4 years of software testing experience and interviews with more than 20 companies after job hopping
idea中debug时如何进入指定的用户方法体中?
【Oracle实训】-部署号称零停机迁移的OGG
JVM学习----内存结构----程序计数器&虚拟机栈&本地方法栈&堆&方法区
How to implement Devops with automation tools | including low code and Devops application practice
How to configure the legendary SF lander to automatically read the list without a network
About: get the domain controller of the current client login
How to block the legendary GEE engine version? Close player account tutorial through script + engine
【HCIE安全】双机热备-主备备份
MySQL的JDBC操作及入门案例
留存收益率计算公式
idea中设置核心配置文件的模板
Cfdiv1+2-pathwalks- (tree array + linear DP)
event.preventDefault VS return false
Multivariable time series prediction using LSTM -- problem summary
Svn uses fragmented ideas
JVM learning - memory structure - program counter & virtual machine stack & local method stack & heap & method area
Flutter Performance Optimization Practice - UI chapter
立即报名:7 月 29 日推荐系统峰会 2022