一、知识要点
![QQ20190403-101109.gif](https://img.haomeiwen.com/i80578/55c45d6c29ecd699.gif?imageMogr2/auto-orient/strip)
二、源码参考
<!DOCTYPE >
<html>
<head>
<title></title>
<meta charset="utf-8">
<script>
window.onload = function() {
var oTab = document.getElementById('tab1');
var oTbody = oTab.tBodies[0];
var oName = document.getElementById('name'); // 姓名
var oOrderBtn = document.getElementById('order'); // 搜索(按钮)
oOrderBtn.onclick = function() {
// 1、缓存元素对象数组
var arr = [];
for(var i = 0; i < oTbody.rows.length; i++) {
arr[i] = oTbody.rows[i];
}
// 2、元素对象数组重写排序
arr.sort(function(tr1, tr2) {
var n1 = parseInt(tr1.cells[0].innerHTML);
var n2 = parseInt(tr2.cells[0].innerHTML);
return n1 - n2;
})
// 3、重新添加元素对象
for(var i = 0; i < oTbody.rows.length; i++) {
oTbody.appendChild(arr[i]);
}
}
}
</script>
</head>
<body>
<input type="button" name="order" id="order" value="排序" />
<table id="tab1" width="300" border="1">
<thead>
<td>ID</td>
<td>姓名</td>
<td>年龄</td>
</thead>
<tbody>
<tr>
<td>4</td>
<td>Blue</td>
<td>27</td>
</tr>
<tr>
<td>5</td>
<td>张三</td>
<td>23</td>
</tr>
<tr>
<td>3</td>
<td>李四</td>
<td>28</td>
</tr>
<tr>
<td>1</td>
<td>王五</td>
<td>25</td>
</tr>
<tr>
<td>2</td>
<td>张伟</td>
<td>24</td>
</tr>
</tbody>
</table>
</body>
</html>
三、运行效果
QQ20190403-101109.gif
网友评论