【发布时间】:2023-02-23 04:54:56
【问题描述】:
我真的可以使用更精通 Javascript 和排序算法的人的第二双眼睛。
我正在尝试按日期 (mm/dd/yyyy) 对我的表格进行排序
这个解决方案对于升序非常有效,即使在我们更大的数据表上也是如此,但是当我切换到降序的小于号时,它在一定程度上起作用。
较小的数据集工作正常,但较大的数据集只会堵塞循环。我不确定这里的断开连接是什么。这特别令人困惑,因为升序工作正常。
WebApp.sortDateReverse = function(colNam, colNum)
{
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("myTable");
switching = true;
console.log('This is colNum', colNum);
console.log('This is colName', colNam);
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done
switching = false;
rows = table.rows;
/*Loop through all table rows (except the
first, which contains table headers):*/
for(i = 1;i<(rows.length - 1);i++) {
//start by saying there should be no switching:
shouldSwitch = false;
console.log('This is i:', i);
console.log('This is row length:', rows.length);
/*Get the two elements you want to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[colNum];
y = rows[i + 1].getElementsByTagName("TD")[colNum];
//check if the two rows should switch place:
if (WebApp.convertDate(x.innerHTML) < WebApp.convertDate(y.innerHTML)) {
//if so, mark as a switch and break the loop:
//console.log('Switching x:', x.innerHTML , 'with y:', y.innerHTML);
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/*If a switch has been marked, make the switch
and mark that a switch has been done:*/
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
};
WebApp.convertDate = function(d) {
return Date.parse(d)
};
【问题讨论】:
-
所以你直接在 DOM 中对元素进行排序?那很不寻常。难道没有数据模型可以排序,DOM重新渲染吗?如果您执着于对 DOM 元素进行排序,我不会尝试使用 DOM 作为您的商店对所有元素进行实时洗牌。只需获取所有元素,使用
arr.sort(...)(内存中)将它们排序为数组,然后通过一次操作将它们转储回 DOM。 -
一些注意事项:您需要 textContent,而不是 innerHTML。此外,如果您要排序,最简单的方法是使用内置的
sort(例如const list = Array.from(table.querySelectorAll("tr")); list.sort((a,b) => { ... });,然后在排序后运行 forEach 将每一行附加到表中(作为附加一个已经存在的元素DOM移动该元素代替)。 -
我将重新评估我的方法并使用
array.sort()方法。我会回来完全重写。希望它能帮助一些人。有时我真的需要另一个视角。
标签: javascript html sorting