HTML
<table id="info"> <tr> <th>姓名</th> <th><a href="javascript:void(0)" onclick="sortTable()">年龄</a></th> <th>地址</th> </tr> <tr> <td>张三</td> <td>27</td> <td>上海</td> </tr> <tr> <td>小强</td> <td>6</td> <td>北京</td> </tr> <tr> <td>李四</td> <td>29</td> <td>广州</td> </tr> <tr> <td>孙八</td> <td>23</td> <td>南京</td> </tr> <tr> <td>二麻子</td> <td>24</td> <td>大连</td> </tr> <tr> <td>犀利姐</td> <td>32</td> <td>青岛</td> </tr> <tr> <td>旺财</td> <td>19</td> <td>深圳</td> </tr> <tr> <td>周七</td> <td>42</td> <td>铁岭</td> </tr> </table>
CSS
table{ border:#249bdb 1px solid; 500px; border-collapse:collapse; } table td{ border:#249bdb 1px solid; padding:10px; } table th{ border:#249bdb 1px solid; padding:10px; background-color: rgb(200,200,200); } th a:link,th a:visited{ color:#279bda; text-decoration:none; } input{ margin-top: 20px; }
JS
/* * 思路: * 1,排序就需要数组。获取需要参与排序的行对象数组。 * 2,对行数组中的每一个行的年龄单元格的数据进行比较,并完成行对象在数组中的位置置换。 * 3,将排好序的数组重新添加回表格。 */ var oTabNode=document.getElementById("info"); var collTrNode=oTabNode.rows; var Btn=document.getElementsByTagName("input"); //定义一个临时容器,存储需要排序行对象。 var trArr=[]; //遍历原行集合,并将需要排序的行对象存储到临时容器中。 //i初始值等于1,去除标题行 for (var i=1;i<collTrNode.length;i++) { trArr[i-1]=collTrNode[i]; } //对临时容器排个序。 mySort(trArr); //点击升序:从小到大排列 Btn[0].onclick=function(){ for (var i=0;i<trArr.length;i++) { trArr[i].parentNode.appendChild(trArr[i]); } } //点击降序:从大到小排列 Btn[1].onclick=function(){ for (var i=trArr.length-1;i>=0;i--) { trArr[i].parentNode.appendChild(trArr[i]); } } //排序函数 function mySort(arr){ for (var i=0;i<arr.length;i++) { for (var j=i+1;j<arr.length;j++) { //按照年龄数值排序,并转成整数。 if(parseInt(arr[i].cells[1].innerHTML)>parseInt(arr[j].cells[1].innerHTML)){ var temp=arr[i]; arr[i]=arr[j] arr[j]=temp; } } } }