日期:2014-05-16 浏览次数:20493 次
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>自动按年龄排序</title> <meta http-equiv="content-type" content="text/html;charset=gb2312" /> <style type="text/css"> table{border:1px solid #dcdcdc;width:600px;} td,th{border:1px solid #999;text-align:center;} th,th a{background:blue;color:#fff;} </style> <script> var zhi = true; function sorttable(){ var tabnode = document.getElementsByTagName("table")[0]; var trs = tabnode.rows; var arr = new Array (); for ( var x =1;x<trs.length ;x++ ){ arr[x-1] = trs[x]; } sortt(arr); var tbdnode = tabnode.childNodes[0]; if(zhi){ for (var x = 0;x<arr.length ;x++ ){ tbdnode.appendChild(arr[x]); } zhi = false; }else{ for (var x = arr.length-1;x>=0 ;x-- ){ tbdnode.appendChild(arr[x]); } zhi = true; } } function sortt(arr){ for(var x = 0;x<arr.length;x++){ for(var y=x+1;y<arr.length;y++){ if(parseInt(arr[x].cells[1].innerText)>parseInt(arr[y].cells[1].innerText)){ var temp = arr[x]; arr[x] = arr[y]; arr[y] =temp; } } } } </script> </head> <!--body开始--> <body> <table> <tr> <th>姓名</th> <th><a href="javascript:void(0);" onclick="sorttable()">年龄</a><sub>▼</sub></th> <th>家乡</th> </tr> <tr> <td>张三</td> <td>33</td> <td>湖南</td> </tr> <tr> <td>李四</td> <td>28</td> <td>广东</td> </tr> <tr> <td>王五</td> <td>23</td> <td>北京</td> </tr> <tr> <td>赵六</td> <td>25</td> <td>四川</td> </tr> <tr> <td>周七</td> <td>35</td> <td>重庆</td> </tr> <tr> <td>孙八</td> <td>26</td> <td>河北</td> </tr> </table> </body> </html>
//var tbdnode = tabnode.childNodes[0]; var tbdnode = tabnode.getElementsByTagName('tbody')[0];
------解决方案--------------------
1楼正解,还有一点需要注意,如果年龄列没有html标签,推荐用innerHTML(innerText在早期的火狐中不被支持,火狐支持的是textContent),改写了一下排序方法
var sortId=1; function sorttable(){ var table=document.getElementsByTagName("table")[0], tbody, trs=table.rows, trHead=trs[0], rows=[], i=1, len=trs.length; if(len<=2) return; tbody=trHead.parentNode; for(;i<len;i++){ rows.push(trs[i]); }