我有一个表,我正在尝试按列(名字),(年龄)对其进行排序。我找不到问题所在。
document.addEventListener('DOMContentLoaded', () => {
const table = document.querySelector('.table');
const indexToSorting = [...table.tHead.rows[0].cells].findIndex(cell => cell.classList.contains('first'));
const availableIndexes = [...table.tHead.rows[0].cells].findIndex(cell => cell.classList.contains('second'));
const sortedRows = [...table.tBodies[0].rows].sort((rowA, rowB) => {
const cellA = rowA.cells[indexToSorting].innerText;
const cellB = rowB.cells[indexToSorting].innerText;
const rowAAvailable = rowA.cells[availableIndexes].innerText;
const rowBAbailable = rowB.cells[availableIndexes].innerText;
const nameComparison = cellA.localeCompare(cellB);
const availableComparison = rowAAvailable.localeCompare(rowBAbailable);
return nameComparison !== 0 ? nameComparison : availableComparison
});
sortedRows.forEach(r => table.tBodies[0].append(r));
});
<table class="table">
<thead>
<tr>
<th class="first">FirstName</th>
<th class="second">Age</th>
<th>Address</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>firstname1</td>
<td>2</td>
<td>ccdd</td>
</tr>
<tr>
<td>nnnxbxc</td>
<td>10</td>
<td>sdjk</td>
</tr>
<tr>
<td>firstname1</td>
<td>100</td>
<td>d</td>
</tr>
<tr>
<td>firstname1</td>
<td>1</td>
<td>ddd</td>
</tr>
</tbody>
</table>
1 个回答