我对此非常陌生,但我的项目必须创建一个可以点击
排序的表格我发现了这个:https://www.w3schools.com/howto/howto_js_sort_table.asp
我已经尝试过,但在这里遇到了一些问题:
我的表有4个标题:名称(Varchar)数字(Varchar)类型(Varchar)价格(INT)
在前3个标题中,点击后它可以正常工作,并且ASC> DESC或DESC> ASC。
问题是最后一个价格(INT)如1 10 11 12 2 3 4 40 5
我已经看了一天,我不能靠自己来解决它:(
所以这里的任何人都可以帮助我或指导我错过的内容吗?
编辑:我的代码
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.getElementsByTagName("TR");
/* Loop through all table rows (except the
first, which contains table headers): */T
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;
}
}
}
}
&#13;
echo "<table id='myTable' border='0' width='570px' align='center'>
<tr>
<th onclick='sortTable(0)'> Number </th>
<th onclick='sortTable(1)'> Name </th>
<th onclick='sortTable(2)'> Type </th>
<th onclick='sortTable(3)'> Price </th>
</tr>";
while($row = $rs_result->fetch_assoc()) {
echo "<tr class='item'>";
echo "<td>".$row['ProductNumber']."</td>";
echo "<td>".$row['ProductName']."</td>";
echo "<td>".$row['TypeName']."</td>";
echo "<td>".$row['ProductPrice']."</td>";
}
echo "</table>";
&#13;
答案 0 :(得分:0)
一个问题可能是您将整数排序为字符串值而不是整数值。 (这可以解释为什么它们按照您看到的方式排序:1 10 11 12 2 3 4 40 5)确保排序将数字排序为整数而不是这些数字的字符串值将列强制转换为列表整数或将每个元素转换为整数。 您将需要创建另一种方法或将当前方法添加为将数字排序为整数的方法。因此,不是调用相同的排序,而是仅在最后一列上调用SortInt。这应该正确排序数字。
更改新排序功能中的if语句。 从:
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase())
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase())
为:
if (parseInt(x.innerHTML, 10) > parseInt(y.innerHTML, 10))
if (parseInt(x.innerHTML, 10) < parseInt(y.innerHTML, 10))