我在html / javascript中有此代码,我正在尝试使用它对database.json中的表进行排序。代码来自:https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_table_desc 由于某种原因,它在运行时会随机对名称进行排序(例如W N C G I-首字母缩写)。我能做什么?任何帮助将不胜感激! :D
<div class="table-responsive">
<table class="table table-striped" id="myTable" >
<thead>
<tr>
% for k in displaykeys:
<th scope="col" style="padding-left:30px">{{k.title()}}</th>
% end # Usual python indention to structure code does not work in
.tpl files - "end" is used instead to end a block
</tr>
</thead>
<tbody>
% for i, d in enumerate(displaydata): # displaydata is expected to be a list of dictionaries
% link_url = "/events/" + str(i + 1) # relative url to detailed view
<tr>
% for k in displaykeys: # Go thru the keys in the same order as for the headline row
<td style="padding-left:30px"><a href="{{link_url}}" alt="See details">{{displaydata[i][k]}}</a></td>
% end # Usual python indention to structure code does not work in .tpl files - "end" is used instead to end a block
</tr>
% end
</tbody>
</table>
</div>
<script>
function sortTable(n) {
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")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
/*check if the two rows should switch place,
based on the direction, asc or desc:*/
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;
}
}
}
}
</script>
<body>
<p><button onclick="sortTable(1)" class="button button2">Sort table</button>
</p>
</body>