所以我在我的 PHP 頁面中有一個 HTML 表(從 MySQL 資料庫填充)和一個特定的列,我想通過單擊列標題對其進行數字排序。按字母順序,排序功能沒有問題。從數值上看,排序功能僅在我放置沒有超鏈接的資料時才起作用。這是表格(有和沒有超鏈接):
<table class="table table-bordered table-striped table-hover" id="myTable">
<thead class="thead-dark">
<tr style="cursor: pointer;">
<th onclick="sortTableId()">ID</th>
<th onclick="sortTable(1)">Titre</th>
<th onclick="sortTable(2)">Date de création</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row[0];?></td>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<table class="table table-bordered table-striped table-hover" id="myTable">
<thead class="thead-dark">
<tr style="cursor: pointer;">
<th onclick="sortTableId()">ID</th>
<th onclick="sortTable(1)">Titre</th>
<th onclick="sortTable(2)">Date de création</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><a href=petition-admin.php?id=<?php echo $row[0]?>'><?php echo $row[0]; ?></a></td>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
和 JavaScript 排序功能:
function sortTableId() {
var table, rows, switching, i, x, y, a, b, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i ) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[0];
y = rows[i 1].getElementsByTagName("TD")[0];
if (dir == "asc") {
if (Number(x.innerHTML) > Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
}
else if (dir == "desc") {
if (Number(x.innerHTML) < Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i 1], rows[i]);
switching = true;
switchcount ;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
表格截圖: 表格
uj5u.com熱心網友回復:
您正在使用innerHTML它將包含內部 HTML 標記,因此數字轉換將是……有趣的。
使用innerText或textContent代替。
例如:
if (Number(x.innerText) > Number(y.innerText))
如果您想變得真正花哨,您可以添加一個data-sortdata資料屬性,也許還可以添加一個data-sortdatatype屬性來處理貨幣(4,000.00 美元)布林值或單元格中的影像(想想布林值的復選標記等)并在這些上執行排序而不是在單元格中標記
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/465300.html
標籤:javascript php 排序
