一、知识
appendChild():先删除,在排序
sort():数组排序
parseInt(): 将字符串==》整数(数字)
!!!- HTML
<input id="btn1" type="button" value="排序" />
<table id="tab1" border="1" width="500">
<thead>
<td>ID</td>
<td>姓名</td>
<td>年龄</td>
<td>操作</td>
</thead>
<tbody>
<tr>
<td>2</td>
<td>张三</td>
<td>23</td>
<td></td>
</tr>
<tr>
<td>6</td>
<td>王四</td>
<td>24</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>Blue</td>
<td>27</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td>张伟</td>
<td>24</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td>李四</td>
<td>28</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td>王五</td>
<td>25</td>
<td></td>
</tr>
</tbody>
</table>
!!! JS
window.οnlοad=function ()
{
var oTab=document.getElementById('tab1');
var oBtn=document.getElementById('btn1');
oBtn.οnclick=function ()
{
var arr=[]; //先创建一个空数组,里面存放的是要排序的值
for(var i=0;i<oTab.tBodies[0].rows.length;i++)
{
arr[i]=oTab.tBodies[0].rows[i]; //数组得到了表格里面的数据
}
arr.sort(function (tr1, tr2){
var n1=parseInt(tr1.cells[0].innerHTML);
var n2=parseInt(tr2.cells[0].innerHTML);
return n1-n2;
});
for(var i=0;i<arr.length;i++)
{
oTab.tBodies[0].appendChild(arr[i]);
}
};
};