当前位置:网站首页>通过单击表头对表进行排序
通过单击表头对表进行排序
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';
...
};边栏推荐
- SPI configuration
- MySQL的JDBC操作及入门案例
- 记一次invalid bound statement xxxxxx 问题解决思路
- JVM learning - memory structure - program counter & virtual machine stack & local method stack & heap & method area
- ROS2节点通信实现零拷贝
- 苹果官网罕见打折,iPhone13全系优惠600元;国际象棋机器人弄伤对弈儿童手指;国内Go语言爱好者发起新编程语言|极客头条
- What are the characteristics of low code tools? The two development tracks of low code that can be seen by discerning people!
- Browser browser cache
- Today, the company came across an Alibaba P8, which was really seen as the ceiling of the foundation
- 洛谷-线段覆盖-(区间排序问题总结)
猜你喜欢

留存收益率计算公式
![[hero planet July training leetcode problem solving daily] 26th and check the collection](/img/f1/e63b1f35b883274ca077cbd2ab4c24.png)
[hero planet July training leetcode problem solving daily] 26th and check the collection

串口通信失败

Flutter性能优化实践 —— UI篇

Daily practice ----- there is a group of students' grades. Arrange them in descending order. To add a student's grade, insert it into the grade sequence and keep the descending order

idea中检索此方法中有哪些参数以便我们使用——1.类图。2.双击shift

After chatting with byte programmers with a monthly salary of 3W, I realized that I had been doing chores

LeetCode 练习——剑指 Offer II 005. 单词长度的最大乘积

牛客刷题——Mysql系列
![[HCIA security] NAT network address translation](/img/10/3b4d011963e00229d73a7435ce8c4b.png)
[HCIA security] NAT network address translation
随机推荐
Ros2 node communication realizes zero copy
idea中设置核心配置文件的模板
LeetCode 练习——剑指 Offer II 005. 单词长度的最大乘积
LiveDatade的基本使用
Error in render: “TypeError: data.slice is not a function“
SPI configuration
TypeScript中的类型断言
[download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng
牛客多校-Journey-(建图distra+卡常优化)
6种方法帮你搞定SimpleDateFormat类不是线程安全的问题
和月薪3W的字节程序员聊过后,才知道自己一直在打杂...
Summary of common interview questions on computer network, including answers
Why does it system need observability?
SPI配置
encodeURI VS encodeURIComponent
Props with type Object/Array must...
kubernetes之Deployment
25张炫酷交互图表,一文入门Plotly
【HarmonyOS议题资料下载】HDD杭州站·线下沙龙专注应用创新 展现鸿蒙生态魅力
今天公司碰到一个阿里p8,算是真正见识到了基础的天花板