我想创建一个HTML表来显示用户状态,它具有三个状态“通过,处理中和失败”,希望用户可以单击状态,它可以按状态对第一个-> Pass,第二个-> Fail进行排序第三->处理中。而不是由A到Z的订单。谢谢
这是我的html代码,
<table border="1">
<th>Name</th>
<th>Status</th>
<tr>
<td>Peter</td>
<td>Pass</td>
</tr>
<tr>
<td>Billy</td>
<td>In process</td>
</tr>
<tr>
<td>Andy</td>
<td>Fail</td>
</tr>
<tr>
<td>Tom</td>
<td>In process</td>
</tr>
<tr>
<td>Mary</td>
<td>Pass</td>
</tr>
以下是我希望最终的输出结果是
但是我在w3school中找到了解决方案
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_table
和其他网站,我找不到解决方案,所以希望有人可以帮助我,谢谢
最佳答案
您可以保持阵列中状态的顺序,并检查它们在阵列中的位置(索引)以进行切换。
我已经更改了w3school代码。
<!DOCTYPE html>
<html>
<title>Sort a HTML Table Alphabetically</title>
<body>
Click on Status cell to Sort
<table border="1" id="myTable">
<th>Name</th>
<th onclick="sortTable()">Status</th>
<tr>
<td>Peter</td>
<td>Pass</td>
</tr>
<tr>
<td>Billy</td>
<td>In process</td>
</tr>
<tr>
<td>Andy</td>
<td>Fail</td>
</tr>
<tr>
<td>Tom</td>
<td>In process</td>
</tr>
<tr>
<td>Mary</td>
<td>Pass</td>
</tr>
</table>
<script>
function sortTable() {
var orderStatus = ["pass","fail", "in process"];
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("myTable");
switching = true;
/*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.getElementsByTagName("TR");
/*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")[1];
y = rows[i + 1].getElementsByTagName("TD")[1];
//check if the two rows should switch place:
if (orderStatus.indexOf(x.innerHTML.toLowerCase()) > orderStatus.indexOf(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;
}
}
}
</script>
</body>
</html>