如何使用JavaScript或jquery根据HTML中列标题的字母顺序交换整个列?
代码:
<body>
<table id="mytable">
<tr>
<th>abc</th>
<th>pqr</th>
</tr>
<tr>
<td>123</td>
<td>345</td>
</tr>
<tr>
<td>987</td>
<td>235</td>
</tr>
</table>
</body>
实际:
abc pqr
123 456
987 235
预期:
pqr abc
456 123
235 987
我尝试了行进中的行:
我为列尝试了此操作,但没有得到结果:-
<script>
function sortTable() {
var table, rows, switching, i, j, temp, x, y, shouldSwitch;
table = document.getElementById("myTable");
rows=table.getElementsByTagName("TR");
var col_length= table.getElementsByTagName("TD").length;
var row_length= table.getElementsByTagName("TR").length;
while (switching) {
switching = false;
r = table.getElementsByTagName("TR");
headers=table.getElementsByTagName("TH");
values=table.getElementsByTagName("TD");
rows=table.rows;
for (i = 0; i < (row_length); i++) {
shouldSwitch = false;
one from current row and one from the next:*/
x = rows[0].getElementsByTagName("TH")[i];
y = rows[0].getElementsByTagName("TH")[i+1];
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
temp=headers[i+1].innerHTML;
headers[i+1].innerHTML=headers[i].innerHTML;
headers[i].innerHTML=temp;
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
and mark that a switch has been done:*/
for(j=0;j<col_length/row_length;j++)
{
values[j].parentNode.insertBefore(values[j + 1], values[j]);
switching = true;
}
}
}
}
</script>
现在有人可以帮我吗?