- 此问题在此处已有答案**:
(17个答案)
How to sort table rows using Javascript(3个答案)
4天前关闭。
我真的需要一个更精通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)
};
1条答案
按热度按时间q1qsirdb1#
多亏了上面的帮助,我才能把这个排序修改成一个更干净、更快的函数,因为我的数据表已经是升序的了,所以我所要做的就是把元素放入一个数组中,然后运行一个
reverse()
,然后运行一个for循环,把反向排序的元素加回表中。现在是修改升序排序函数的时候了。