我想在表中显示一个名称数组。就像时间表一样,我有一个排序按钮,因为如果我想添加一个新的Student,则应该将Student分类在正确的位置。 我的数组包含此值
但是如果我按下排序按钮,输出就是这样
该剂量没有上升和下降的意义
这是代码
function sort(){
students.sort();
for(var i = 0;i<students.length+1;i++){
if(i!=0){
alert(students[i-1].innerHTML);
<!table.rows[i].cells[0].innerHTML=students[i1].innerHTML;>
}
}
}
答案 0 :(得分:2)
如果您要对现有表格的行进行排序-这是一种更好的方法
document.getElementById('sort1').addEventListener('click', () => {
let tableBody = document.querySelector('#table>tbody');
let rows = [...tableBody.querySelectorAll('#table>tbody>tr')];
rows
.sort((a, b) => a.cells[0].textContent.localeCompare(b.cells[0].textContent))
.forEach(row => tableBody.append(row));
});
document.getElementById('sort2').addEventListener('click', () => {
let tableBody = document.querySelector('#table>tbody');
let rows = [...tableBody.querySelectorAll('#table>tbody>tr')];
rows
.sort((a, b) => a.cells[2].textContent.localeCompare(b.cells[2].textContent))
.forEach(row => tableBody.append(row));
})
<table id="table">
<tbody>
<tr>
<td>Delta</td>
<td>Alpahbetically 4th</td>
<td>Rank 2nd</td>
</tr>
<tr>
<td>Bravo</td>
<td>Alpahbetically 2nd</td>
<td>Rank 1st</td>
</tr>
<tr>
<td>Charlie</td>
<td>Alpahbetically 3rd</td>
<td>Rank 4th</td>
</tr>
<tr>
<td>Alpha</td>
<td>Alpahbetically 1st</td>
<td>Rank 3rd</td>
</tr>
</tbody>
</table>
<button id="sort1">Sort by name</button>
<button id="sort2">Sort by rank</button>