你可以保持状态的顺序在数组和检查,以切换或者不是他们的阵列中的位置(索引)。 我已经改变了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>
您使用的数据表jQuery库? –