<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
window.onload = function(){
var input = document.querySelectorAll('input');
var table = document.querySelector('table');
var rows = table.tBodies[0].rows;
var arrRows = [];
/* 因为只能对数组排序,所以把tr都放入数组 */
for(var i = 0; i < rows.length; i++){
arrRows.push(rows[i]);
}
// arrRows.sort(function(a,b){
// return b.cells[1].innerHTML - a.cells[1].innerHTML;
// //根据tr中的第1个单元格中的内容进行排序
// });
// arrRows.forEach(function(tr){
// //按照排号的顺序,重新把tr放入tbody
// table.tBodies[0].appendChild(tr);
// });
//console.log(arrRows);
input[0].onclick = function(){
arrRows.sort(function(a,b){
return b.cells[1].innerHTML - a.cells[1].innerHTML;
//根据tr中的第1个单元格中的内容进行排序
});
arrRows.forEach(function(tr){
//按照排号的顺序,重新把tr放入tbody
table.tBodies[0].appendChild(tr);
});
}
input[1].onclick = function(){
arrRows.sort(function(a,b){
return a.cells[1].innerHTML - b.cells[1].innerHTML;
//根据tr中的第1个单元格中的内容进行排序
});
arrRows.forEach(function(tr){
//按照排号的顺序,重新把tr放入tbody
table.tBodies[0].appendChild(tr);
});
}
};
</script>
</head>
<body>
<table border="1" width="400" align="center">
<thead>
<tr>
<th>水果</th>
<th>单价(¥)</th>
</tr>
</thead>
<tbody>
<tr>
<th>苹果</th>
<th>54.5</th>
</tr>
<tr>
<th>橘子</th>
<th>24.5</th>
</tr>
<tr>
<th>西瓜</th>
<th>33.8</th>
</tr>
<tr>
<th>香蕉</th>
<th>13.8</th>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2" style="text-align: center;">
<input type="button" value="价格从高到低排列">
<input type="button" value="价格从低到高排列">
</td>
</tr>
</tfoot>
</table>
</body>
</html>

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!