テーブルで並べ替えを使用しようとしています。私は以下のメソッドを使用していますが、メソッドを使用して数値をソートする際にエラーがあります。この方法は適切に機能しますが、数字ASCとDESCの順序で発行されます。私はなぜこれを起こすのか分からなかった。みんな、これについて何か考えている?javascriptで数字を並べ替える方法
function sortTable(n, selector) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
///table = document.getElementById(selector);
table = $(selector);
switching = true;
//Set the sorting direction to ascending:
dir = "asc";
/*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).find('tr'); ///table.getElementsByTagName("TR");
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 0; i < (rows.length - 1) ; i++) {
//start by saying there should be no switching:
shouldSwitch = false;
/*Get the two elements you want to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
/*check if the two rows should switch place,
based on the direction, asc or desc:*/
if (x != null && y != null) {
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
//if so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
//if so, mark as a switch and break the loop:
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;
//Each time a switch is done, increase this count by 1:
switchcount++;
} else {
/*If no switching has been done AND the direction is "asc",
set the direction to "desc" and run the while loop again.*/
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
.find( 'TR')'は 'table.rows'を使用することは非常にはるかに効率的で、そして代わりに、'行[i]との。 getElementsByTagName( "TD")[n] '行[i] .cells [n]'とみなします。他に何も入力しないでください。 ;-)これはバブルソートであり、非常に非効率的です。ソートする行を配列に入れ、* Array.prototype.sort *を使用してソートし、ソート順に並べ替えることを検討してください。 – RobG