Я пытаюсь добавить символы сортировки в мою таблицу HTML. Ниже мой Javascript код.
function sortTableRowsByColumn( table, columnIndex, ascending ) {
const rows = Array.from( table.querySelectorAll( ':scope > tbody > tr' ) );
rows.sort( ( x, y ) => {
const xValue = x.cells[columnIndex].textContent;
const yValue = y.cells[columnIndex].textContent;
const xNum = parseFloat( xValue );
const yNum = parseFloat( yValue );
return ascending ? ( xNum - yNum ) : ( yNum - xNum );
} );
for( let row of rows ) {
table.tBodies[0].appendChild( row );
}
}
function onColumnHeaderClicked( ev ) {
const th = ev.currentTarget;
const table = th.closest( 'table' );
const thIndex = Array.from( th.parentElement.children ).indexOf( th );
const ascending = !( 'sort' in th.dataset ) || th.dataset.sort != 'asc';
sortTableRowsByColumn( table, thIndex, ascending );
const allTh = table.querySelectorAll( ':scope > thead > tr > th' );
for( let th2 of allTh ) {
delete th2.dataset['sort'];
}
th.dataset['sort'] = ascending ? 'asc' : 'desc';
}
Вот мой html для таблицы.
<table id="table" class="table table-striped table-bordered table-sm" style="font-size: 50%;">
<thead>
<tr>
<th onclick="onColumnHeaderClicked(event)" scope="col">Klant </th>
<th scope="col">Adres</th>
<th onclick="onColumnHeaderClicked(event)" scope="col"># panelen</th>
</tr>
</thead>
Моя сортировка работает полностью нормально. Однако, чтобы сделать его более интуитивным, я хочу добавить символы сортировки в мой заголовок. Кто-нибудь может предложить способ сделать это?