




关注让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如需一对一服务私聊我哦问题描述:如何在前端实现一个表格排序功能? 解决方案:
const tableData = [
{ id: 1, name: 'Tom', age: 20, score: 90 },
{ id: 2, name: 'Jerry', age: 22, score: 85 },
{ id: 3, name: 'Mike', age: 21, score: 95 },
{ id: 4, name: 'Lisa', age: 19, score: 88 }
];
function sortTableData(data, column, order) {
const columnIndex = typeof column === 'number' ? column : Object.keys(data[0]).indexOf(column);
const sortedData = data.sort((a, b) => {
if (a[columnIndex] < b[columnIndex]) {
return order === 'DESC' ? 1 : -1;
}
if (a[columnIndex] > b[columnIndex]) {
return order === 'DESC' ? -1 : 1;
}
return 0;
});
return sortedData;
}
// 按年龄升序排序
const ageAscData = sortTableData(tableData, 'age', 'ASC');
// 按成绩降序排序
const scoreDescData = sortTableData(tableData, 3, 'DESC');
<table id="table">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄 <button class="sort-btn" data-col="age">升序</button></th>
<th>成绩 <button class="sort-btn" data-col="score">升序</button></th>
</tr>
</thead>
<tbody>
<!-- 表格内容 -->
</tbody>
</table>
JavaScript:
// 获取表格元素
const table = document.querySelector('#table');
// 获取排序按钮列表
const sortBtnList = table.querySelectorAll('.sort-btn');
// 根据指定的列和排序方式更新表格数据和排序按钮状态
function updateTableData(column, order) {
const sortedData = sortTableData(tableData, column, order);
const tbody = table.querySelector('tbody');
while (tbody.firstChild) {
tbody.removeChild(tbody.firstChild);
}
sortedData.forEach(rowData => {
const tr = document.createElement('tr');
Object.values(rowData).forEach(cellData => {
const td = document.createElement('td');
td.textContent = cellData;
tr.appendChild(td);
});
tbody.appendChild(tr);
});
// 更新排序按钮状态
sortBtnList.forEach(btn => {
if (btn.dataset.col === column) {
btn.dataset.order = order;
btn.textContent = order === 'ASC' ? '升序' : '降序';
} else {
btn.dataset.order = 'ASC';
btn.textContent = '升序';
}
});
}
// 添加事件监听器
sortBtnList.forEach(btn => {
btn.addEventListener('click', () => {
const column = btn.dataset.col;
const order = btn.dataset.order === 'ASC' ? 'DESC' : 'ASC';
updateTableData(column, order);
});
});
// 初始化表格
updateTableData('id', 'ASC');