有道笔试题,点击表头进行对成绩升序或降序
约定下表格标签结构 table>tr>th tr>td
比较懒就不封装了
假设HTML结构如下
<table>
<tr>
<th>名字</th>
<th>性别</th>
<th>成绩</th>
</tr>
<tr>
<td>a</td>
<td>girl</td>
<td>86</td>
</tr>
<tr>
<td>b</td>
<td>boy</td>
<td>95</td>
</tr>
</table>
//1. 获取表格
var table = document.querySelector('table');
var trs = table.querySelectorAll('tr');
var direction = 1;//用来区分升序降序
//2.表格数据转为数组
var list = [];
for(var i = 1;i<trs.length;i++){
var tds = trs[i].querySelectorAll('td');
list.push({name:tds[0].innerText,sex:tds[1].innerText,score:tds[2].innerText})
}
//3.数组排序
(function(){
for(var i =0; i< list.length;i++){
for(var j=i;j<list.length;j++){
if(list[i].score>list[j].score){
var temp = list[i];
list[i] = list[j]
list[j] = temp;
}
}
}
})()
//4.渲染页面,修改innerText,减少dom操作
function render(direction){
if(direction == 1){
for(var i=1;i<trs.length;i++){
var tds = trs[i].querySelectorAll('td');
tds[0].innerText = list[i-1].name;
tds[1].innerText = list[i-1].sex;
tds[2].innerText = list[i-1].score;
}
}else{
for(var i=1;i<trs.length;i++){
var tds = trs[i].querySelectorAll('td');
tds[0].innerText = list[list.length-i].name;
tds[1].innerText = list[list.length-i].sex;
tds[2].innerText = list[list.length-i].score;
}
}
}
//5.事件绑定
table.onclick=function(e){
if(e.target.innerText=='成绩'){
render(direction);direction= -direction;
}
}