当前位置:网站首页>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';
...
};边栏推荐
- Retrieve the parameters in this method in idea for our use -- 1. Class diagram. 2. Double click shift
- 【HarmonyOS议题资料下载】HDD杭州站·线下沙龙专注应用创新 展现鸿蒙生态魅力
- 2022-7-26 第七组 抽象和接口
- Some unexpected bug records
- Devsecops, speed and security
- Flutter性能优化实践 —— UI篇
- Devsecops, speed and security
- We were tossed all night by a Kong performance bug
- 【HCIA安全】用户认证
- Redis interview questions
猜你喜欢

idea中debug时如何进入指定的用户方法体中?
![[HCIA security] user authentication](/img/6f/0ab6287eac36a4647dc2a0646ba969.png)
[HCIA security] user authentication

Live broadcast appointment award | senior consultant xuyanfei: how does efficiency measurement help efficient and sophisticated outsourcing management

功能尝鲜 | 解密 Doris 复杂数据类型 ARRAY

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

一种用于实体关系抽取的统一标签空间

Test cases should never be used casually, recording the thinking caused by the exception of a test case
![[question] browser get request with token](/img/95/f0b7186f930c014495414c3fcdaa6e.png)
[question] browser get request with token

Devsecops, speed and security

LeetCode 练习——剑指 Offer II 005. 单词长度的最大乘积
随机推荐
Practice of microservice in solving Library Download business problems
Sprinboot interview questions
Cfdiv1+2-pathwalks- (tree array + linear DP)
Arm TZ hardware support
<button> 与 <input type=“button“ />
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
ECCV 2022 | complete four tracking tasks at the same time! Unicorn: towards the unification of target tracking
Ros2 node communication realizes zero copy
Props with type Object/Array must...
Devops has been practiced for many years. What is the most painful thing?
TypeScript中的类型断言
Why didn't Tencent create a game like "original God"
Devsecops, speed and security
SPI configuration
[Oracle training] - deploy Ogg known as zero downtime migration
JVM学习----内存结构----程序计数器&虚拟机栈&本地方法栈&堆&方法区
[HCIA security] NAT network address translation
PLSQL package