在JavaScript中实现表格(table)的多列排序通常涉及以下几个基础概念:
Array.prototype.sort()
方法简化排序过程。以下是一个简单的JavaScript实现多列排序的示例:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>多列排序示例</title>
<style>
table {
width: 50%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ccc;
padding: 8px;
text-align: left;
}
th {
cursor: pointer;
}
th.asc::after {
content: " ▲";
}
th.desc::after {
content: " ▼";
}
</style>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th data-key="name">姓名</th>
<th data-key="age">年龄</th>
<th data-key="score">分数</th>
</tr>
</thead>
<tbody>
<tr><td>张三</td><td>25</td><td>85</td></tr>
<tr><td>李四</td><td>30</td><td>90</td></tr>
<tr><td>王五</td><td>25</td><td>80</td></tr>
<!-- 更多行 -->
</tbody>
</table>
<script>
const table = document.getElementById('myTable');
const headers = table.querySelectorAll('th');
let sortStates = {}; // 记录每列的排序状态
headers.forEach(header => {
header.addEventListener('click', () => {
const key = header.getAttribute('data-key');
let direction = 'asc';
if (sortStates[key] === 'asc') {
direction = 'desc';
}
sortTable(key, direction);
updateSortIndicators(key, direction);
});
});
function sortTable(key, direction) {
const tbody = table.querySelector('tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
rows.sort((a, b) => {
const aText = a.querySelector(`td:nth-child(${getColumnIndex(key)})`).textContent;
const bText = b.querySelector(`td:nth-child(${getColumnIndex(key)})`).textContent;
if (isNaN(aText) && isNaN(bText)) {
return direction === 'asc' ? aText.localeCompare(bText) : bText.localeCompare(aText);
} else {
return direction === 'asc' ? aText - bText : bText - aText;
}
});
// 清空现有行并重新添加排序后的行
tbody.innerHTML = '';
rows.forEach(row => tbody.appendChild(row));
}
function getColumnIndex(key) {
return Array.from(headers).findIndex(header => header.getAttribute('data-key') === key) + 1;
}
function updateSortIndicators(activeKey, direction) {
headers.forEach(header => {
header.classList.remove('asc', 'desc');
const key = header.getAttribute('data-key');
if (key === activeKey) {
header.classList.add(direction);
}
});
sortStates[activeKey] = direction;
}
</script>
</body>
</html>
sortStates
)来记录每列当前的排序状态(升序或降序),并在每次排序时更新该状态。实现JavaScript表格的多列排序需要理解DOM操作、事件处理和排序逻辑。通过合理记录排序状态、处理不同数据类型以及优化性能,可以实现高效且用户友好的多列排序功能。上述示例提供了一个基础的实现框架,可以根据具体需求进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云