当前位置:网站首页>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';
...
};边栏推荐
- QT Foundation Day 1 (1) QT, GUI (graphical user interface) development
- Today, the company came across an Alibaba P8, which was really seen as the ceiling of the foundation
- ROS2节点通信实现零拷贝
- Broadcast voice H5 speechsynthesisutterance
- What kind of security problems will the server encounter?
- 6种方法帮你搞定SimpleDateFormat类不是线程安全的问题
- Retrieve the parameters in this method in idea for our use -- 1. Class diagram. 2. Double click shift
- kubernetes之Deployment
- Go+mysql+redis+vue3 simple chat room, the sixth bullet: use vue3 and element plus to call the interface
- Some unexpected bug records
猜你喜欢

idea中检索此方法中有哪些参数以便我们使用——1.类图。2.双击shift
![[question] browser get request with token](/img/95/f0b7186f930c014495414c3fcdaa6e.png)
[question] browser get request with token

微服务化解决文库下载业务问题实践

APaaS低代码平台(一) | 把复杂留给自己,把简单留给用户
![[download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng](/img/62/9e2ff0dc2c8b049fd32ad56334a0c0.jpg)
[download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng

Summary of 4 years of software testing experience and interviews with more than 20 companies after job hopping

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

We were tossed all night by a Kong performance bug

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

How to implement Devops with automation tools | including low code and Devops application practice
随机推荐
JVM learning - memory structure - program counter & virtual machine stack & local method stack & heap & method area
Devsecops, speed and security
Custom annotation (I)
Live broadcast appointment award | senior consultant xuyanfei: how does efficiency measurement help efficient and sophisticated outsourcing management
[question] browser get request with token
Summary of common interview questions of computer composition principle, including answers
Flutter性能优化实践 —— UI篇
TypeScript中的类型断言
JDBC connection
通过单击表头对表进行排序
Number() VS parseInt()
Sprinboot interview questions
[HCIA security] user authentication
Niuke brush questions - MySQL series
kubernetes之Deployment
微服务化解决文库下载业务问题实践
Object.getOwnPropertyNames() VS Object.keys()
Practice of microservice in solving Library Download business problems
Difference between redis hash and string
【打新必读】工大科雅估值分析,供热节能产品