在W3Schools的帮助下,我尝试创建一个过滤器,用于对Marks进行升序和降序排序。
但是它没有排序。并且似乎在以下位置有错误:getElementsByTagName("SPAN").innerHTML
,但我无法解决它。
- 另外**,排序后第一列(Sr.)不应更改!
function sortTable() {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable");
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.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;
/*Get the two elements you want to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[2];
y = rows[i + 1].getElementsByTagName("TD")[2];
/*check if the two rows should switch place,
based on the direction, asc or desc:*/
if (dir == "asc") {
if (Number(x.getElementsByTagName("SPAN").innerHTML) > Number(y.getElementsByTagName("SPAN").innerHTML)) {
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (Number(y.getElementsByTagName("SPAN").innerHTML) > Number(x.getElementsByTagName("SPAN").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;
//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;
}
}
}
}
table {
border-spacing: 0;
width: 100%;
border: 1px solid #ddd;
}
th,
td {
text-align: left;
padding: 16px;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
<p><button onclick="sortTable()">Sort</button></p>
<table id="myTable">
<tr>
<th>Sr</th>
<th>Name</th>
<th>Marks</th>
</tr>
<tr>
<td class="font-elephant">1</td>
<td class="font-elephant">John</td>
<td class="font-elephant"><span>438</span> Passed</td>
</tr>
<tr>
<td class="font-elephant">2</td>
<td class="font-elephant">Kevin</td>
<td class="font-elephant"><span>238</span> Failed</td>
</tr>
<tr>
<td class="font-elephant">3</td>
<td class="font-elephant">Lux</td>
<td class="font-elephant"><span>568</span> Passed</td>
</tr>
<tr>
<td class="font-elephant">4</td>
<td class="font-elephant">Bro</td>
<td class="font-elephant"><span>538</span> Passed</td>
</tr>
</table>
但是它没有排序。并且似乎在以下位置有错误:getElementsByTagName("SPAN").innerHTML
,但我无法解决它。
- 另外**,排序后第一列(Sr.)不应更改!
2条答案
按热度按时间tvz2xvvm1#
下面的脚本按升序和降序对标记进行排序。
gwbalxhn2#
下面是我的解决方案:首先提取每个
span
元素的值,然后使用Array.prototype.sort对它们进行排序,然后将它们重新插入到DOM中。