对于研究项目,我必须使用JavaScript创建动态表。我向一些朋友寻求帮助,但是由于他们既不是我也不是计算机科学家(或者这个方向的任何人),所以我只知道使用AJAX和DOM很好。并使用以下javascipt(src = w3schools和堆栈)
问题它正在排序,但不是字母或数字。它可能是表格一栏中包含的图片的网址,但对我来说,它看起来是随机的。
我如何创建动态工作排序表?
<table id="phones">
<thead>
<th><h2>Brand<br><p>Click to sort</p>
<p><button onclick="sortTable()"></button></p></h2></th>
<th><h2>IMG</h2></th>
<th><h2>Model<br><p>Click to sort</p>
<p><button onclick="sortTable()"></button></p></h2></th>
<th><h2>Os<br><p>Click to sort</p>
<p><button onclick="sortTable()"></button></p></h2></th>
<th><h2>Screensize<br><p>Click to sort</p>
<p><button onclick="sortTable()"></button></p></h2></th>
<th><h2>Price<br><p>Click to sort</p>
<p><button onclick="sortTable()"></button></p></h2></th>
</thead> ```
function sortTable() {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById('phones');
switching = true;
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 (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
getElementsByTagName("TD")[0]
表示访问first TD
元素,但是您并不总是想要第一个。相反,您需要添加一个colNum
parameter,该名称可用于在调用函数时在所定义的方括号中放置一个不同的数字。您还希望将数字排序与字母排序不同。当您将数字视为字符串时,它们的排序方式会有所不同,如下所示:
console.log( ["19", "20", "3", "35", "1", "25", "300"].sort() );
因此添加第二个参数,您可以在其中告诉函数应使用字母排序还是数字排序。然后,在函数中,检测参数并进行相应的排序,如下所示:
function sortTable(colNum, sortType) {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("phones");
switching = true;
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[colNum];
y = rows[i + 1].getElementsByTagName("TD")[colNum];
if (sortType == "alphabetical") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else {
if (Number(x.innerHTML) > Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
<table id="phones">
<tr>
<th><button onclick="sortTable(0, 'alphabetical');">Sort this column</button></th>
<th><button onclick="sortTable(1, 'alphabetical');">Sort this column</button></th>
<th><button onclick="sortTable(2, 'numerical');">Sort this column</button></th>
</tr>
<tr>
<td>C</td>
<td>A</td>
<td>100</td>
</tr>
<tr>
<td>D</td>
<td>Z</td>
<td>1</td>
</tr>
<tr>
<td>E</td>
<td>D</td>
<td>19</td>
</tr>
<tr>
<td>A</td>
<td>C</td>
<td>55</td>
</tr>
</table>