我知道这篇文章有点老了,但这里的 ES6+ 解决方案对我来说非常有用。
/**
* Sort table data based on a direction of asc or desc for a specific column
* @param {number} n- column number calling this sort
* @param {string} dir -direction of the sort (asc or desc)
* @param {HTMLSpanElement} targetElem -sort icon
*/
function sortTable(n, dir = "asc", targetElem) {
targetElem.style.cursor = "progress";
let sortArr = [];
let table =targetElem.closest('table');
table.querySelectorAll('tbody > tr > td:nth-Child(' + parseInt(n) + ')').forEach((x, y) => sortArr.push(
{
sortText: x.innerHTML.toLowerCase(),
rowElement: x.closest('tr')
}));
var sorted = sortArr.sort(function (a, b) {
if (dir == "asc") {
if (a.sortText < b.sortText) {
return -1;
}
} else if (dir == "desc") {
if (a.sortText > b.sortText) {
return -1;
}
}
return 0;
});
sorted.forEach((x, y) => {
x.rowElement.parentNode.insertBefore(x.rowElement, x.rowElement.parentNode.children[y]);
});
targetElem.style.cursor = null;
}
在我的每个元素中,我都有用于调用此函数的排序图标。它们的列号嵌入在数据标签中。他们看着像是:
<th data-field-name="lastLogin" role="columnheader" class="lastLogin">Last Login
<span class="fa fa-unsorted sort-icon" title="Sort Descending" data-col-number="6" style="font-size: 1.2em; margin-left: 15px;"></span>
</th>
图标的点击动作:
click(icon){
var parent = icon.closest('tr');
parent.querySelectorAll('.sort-icon').forEach(x => {
if (x == icon) {
return;
}
delete x.dataset.dir;
x.classList.replace('fa-sort-down', 'fa-unsorted');
x.classList.replace('fa-sort-up', 'fa-unsorted');
});
if (icon.classList.contains('fa-unsorted')) {
icon.classList.replace('fa-unsorted', 'fa-sort-up');
icon.title = icon.title.replace('Ascending', 'Descending');
icon.dataset.dir = "asc";
} else if (icon.classList.contains('fa-sort-down')) {
icon.classList.replace('fa-sort-down', 'fa-sort-up');
icon.dataset.dir = "asc";
icon.title = icon.title.replace('Ascending', 'Descending');
} else if (icon.classList.contains('fa-sort-up')) {
icon.classList.replace('fa-sort-up', 'fa-sort-down');
icon.title = icon.title.replace('Descending', 'Ascending');
icon.dataset.dir = "desc";
}
sortTable(icon.dataset.colNumber, icon.dataset.dir, icon);
}