<div class="codetitle"> <span><a style="CURSOR: pointer" data="959" class="copybut" id="copybut959" onclick="doCopy('code959')"><u>複製程式碼</u></a></span> 程式碼如下:</div> <div class="codebody" id="code959"> <br><script type="text/javascript"> <BR>var bvar bvar = true ; <BR>function sortAge(){ <BR>var tabNode = document.getElementsByTagName("table")[0]; <BR>var trNodes = tabNode.rows; //取得表格中的行物件<BR> var arr = new Array(); <BR>for(var x=1;x<trNodes.length;x ){ //臨時容器存入的是表格中行物件的參考<BR>arr[x-1] = trNodes[x]; <BR>} <BR>sort(arr); <BR>var tbdNode = tabNode.childNodes[0]; <BR>if(b){ //if....else...控制依年齡的升降進行排序<BR>for(var x=0;x<arr.length;x ){ <BR>tbdNode.appendChild(arr[x]); <BR>} <BR>b = false; <BR>}else{ <BR>for(var x=arr.length-1;x>=0;x--){ <BR>tbdNode.appendChild(arr[x]); <BR>} <BR>b = true ; <BR>} <BR>} <BR>function sort(arr){ // 排序<BR>for(var x=0;x<arr.length;x ){ <BR>for(var y= x 1;y<arr.length;y ){ <BR>if(parseInt(arr[x].cells[1].innerText)>parseInt(arr[y].cells[1].innerText)){ //不進行parseInt轉換是以字串的ASCII比較<BR>var temp = arr[x]; <BR>arr[x] = arr[y]; <BR>arr[y] = temp; <BR>} <BR>} <BR>} <BR>} <BR></script> <br><br><style type="text/css"> <BR>table{ width:60%; border:solid 1px #0066FF ;} <BR>table td {border:solid 1px #0099ff;} <BR>a{ text-decoration: none;} <BR></style> <br><br> <br> <br><table> <br><tr> <br><td>姓名</td> <td><a href="javascript:void(0)" onclick="sortAge()">年齡 a></a></td> <td>地址</td> <br> </tr> <br><tr> <br><td>張三</td> <td>23</td> <td>北京</td> <br> </tr> <br><tr> <br><td>李四</td> <td>25</td> <td>上海</td> <br> <br> </tr> <tr> <br><td>王五</td> <td>15</td> <td>廣州</td> <br> </tr> <br><tr> <br><td>唐總</td> <td>20</td> <td>長沙</td> <br> </tr> <br> </table> <br> <br> </div>