<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>表格中的數(shù)據(jù)排序</title> <style type="text/css"> table { border:#0099FF 1px solid; border-collapse:collapse; width:600px; font-family: "微軟雅黑"; margin-top: 50px; } table td{ border:#0099FF 1px solid; text-align:center; } #age:link,#age.visited { color:#000000; } div{ text-align: center; padding:20px; color:red; } </style> <script type="text/javaScript"> function sort(){ //冒泡排序 var aTr = document.getElementsByTagName("tr");//獲取所有的tr //循環(huán)遍歷所有的tr(第一行為表頭不算, i和j從1開始) for(var i=1; i<aTr.length-1; i++){ for(var j=1; j<aTr.length-i; j++){ //獲取第j行的年齡 var age1 = parseInt(aTr[j].getElementsByTagName("td")[1].innerHTML); //獲取第j+1行的年齡 var age2 = parseInt(aTr[j+1].getElementsByTagName("td")[1].innerHTML); //比較年齡 if(age1>age2){//升序排序 /*var temp = aTr[j]; aTr[j] = aTr[j+1]; aTr[j+1] = temp;*/ //這種方式是錯的!!! //1.方式一 /* var cloneAtr1 = aTr[j].cloneNode(true); var cloneAtr2 = aTr[j+1].cloneNode(true); aTr[j].parentNode.replaceChild(cloneAtr1 , aTr[j+1]); aTr[j].parentNode.replaceChild(cloneAtr2 , aTr[j]); */ //2.方式二 var temp = aTr[j].innerHTML; aTr[j].innerHTML = aTr[j+1].innerHTML; aTr[j+1].innerHTML = temp; } } } } </script> </head> <body> <table align="center" cellpadding="10"> <tr> <th>姓名</th> <th onclick="sort()" style="cursor:pointer;">年齡</th> <th>地址</th> </tr> <tr> <td>張三</td> <td>25</td> <td>北京</td> </tr> <tr> <td>李四</td> <td>23</td> <td>天津</td> </tr> <tr> <td>王五</td> <td>28</td> <td>上海</td> </tr> <tr> <td>趙六</td> <td>26</td> <td>南京</td> </tr> <tr> <td>周七</td> <td>22</td> <td>上海</td> </tr> </table> <div>(效果: 試試點擊年齡...表格行會按照年齡大小進(jìn)行排列)</div> </body> </html> |
|