当前位置:网站首页>Sort the table by clicking on the header
Sort the table by clicking on the header
2022-07-26 21:26:00 【Ziwei front end】
Suppose we want to sort any column in the following table :
<table id="sortMe" class="table">
...
</table>Sort the rows
click:// 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) The function sorts all rows by the given column index. So :- We can use
Array'sort()Method to sort the current row - then , Delete All current rows
- and additional Sorted rows
// 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 Method , This method accepts a function to compare two items . In our case , The two cells of the column are based on their HTML Content Compare : newRows.sort(function(rowA, rowB) {
// Get the content of cells
const cellA = rowA.querySelectorAll('td')[index].innerHTML;
const cellB = rowB.querySelectorAll('td')[index].innerHTML;
...
});Other types are supported
<thead>
<tr>
<th data-type="number">No.</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead> for example , Number The column will have a data-type="number" attribute . If the attribute is missing , Then the content type of the cell is string . We need a function to convert the contents of a cell from a string to another type :
// 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 and string Column , But you are free to support more types , For example, date .sortColumn Slightly improve the functionality to support custom content types . We don't compare the original content , Instead, compare values based on content type conversion :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;
}
});
Support two-way
// Track sort directions
const directions = Array.from(headers).map(function (header) {
return '';
});directions Is an array , Each of these items can be asc or desc Indicates the sort direction in the associated column . The sortColumn() The function now involves more logic to compare two lines according to the current direction :
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';
...
};边栏推荐
- 滤波及失真
- Mysql -count :count(1)、count(*)、count(列名)的区别
- idea中检索此方法中有哪些参数以便我们使用——1.类图。2.双击shift
- 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
- Flutter性能优化实践 —— UI篇
- 一些意想不到的bug记录
- 微服务化解决文库下载业务问题实践
- Ros2 method of obtaining current system time
- Deepfake pinches his face. It's hard to tell whether it's true or false. Tom Cruise is more like himself than himself!
- 一种用于实体关系抽取的统一标签空间
猜你喜欢
![[HCIA security] user authentication](/img/6f/0ab6287eac36a4647dc2a0646ba969.png)
[HCIA security] user authentication

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

Browser browser cache

Remember the idea of solving the problem of invalid bound statement xxxxx once

【Oracle实训】-部署号称零停机迁移的OGG

IT系统为什么需要可观测性?

Why didn't Tencent create a game like "original God"

TCP的粘包拆包问题解决方案

The hardest lesson we learned from the crypto Market

How to block the legendary GEE engine version? Close player account tutorial through script + engine
随机推荐
kubernetes之Deployment
2022-7-26 第七组 抽象和接口
立即报名:7 月 29 日推荐系统峰会 2022
2022 open atom global open source summit agenda express | list of sub forum agenda on July 27
制作一个可调整大小的元素
串口通信失败
Niuke brush questions - MySQL series
Why didn't Tencent create a game like "original God"
【HCIA安全】双向NAT
服务器的防护会遇到什么样的安全问题呢?
Basic use of livedatade
Relevant contents about wireless communication
4年软件测试工作经验,跳槽之后面试20余家公司的总结
QT Foundation Day 1 (1) QT, GUI (graphical user interface) development
Soft test --- database (1) database foundation
Modify excel default code
Today, the company came across an Alibaba P8, which was really seen as the ceiling of the foundation
苹果官网罕见打折,iPhone13全系优惠600元;国际象棋机器人弄伤对弈儿童手指;国内Go语言爱好者发起新编程语言|极客头条
除了「加机器」,其实你的微服务还能这样优化
Alkbh1