JS 表格排序--appendChild
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>表格排序</title> 6 <style type="text/css"> 7 table{ 8 width: 300px; 9 text-align: center; 10 } 11 table,td{ 12 border: 1px solid gray; 13 } 14 </style> 15 </head> 16 <body> 17 <button id="btn1">表格排序</button> 18 <table id="table1"> 19 <thead> 20 <tr> 21 <td>ID</td> 22 <td>姓名</td> 23 <td>性别</td> 24 <td>年龄</td> 25 </tr> 26 </thead> 27 <tbody> 28 <tr> 29 <td>4</td> 30 <td>张三</td> 31 <td>男</td> 32 <td>24</td> 33 </tr> 34 <tr> 35 <td>1</td> 36 <td>李四</td> 37 <td>女</td> 38 <td>38</td> 39 </tr> 40 <tr> 41 <td>3</td> 42 <td>张五</td> 43 <td>男</td> 44 <td>25</td> 45 </tr> 46 <tr> 47 <td>2</td> 48 <td>张二</td> 49 <td>女</td> 50 <td>21</td> 51 </tr> 52 </tbody> 53 </table>
54 <script type="text/javascript"> 55 window.onload=function(){ 56 var tab=document.getElementById('table1'); 57 var btn=document.getElementById('btn1'); 58 btn.onclick=function(){ 59 var arr=[]; 60 for(var i=0;i<tab.tBodies[0].rows.length;i++){ 61 arr[i]=tab.tBodies[0].rows[i]; 62 }// sort方法只能应用于array数组类中,所以定义一个arr[],重新定义sort()方法 63 arr.sort(function(tr1,tr2){ 64 var n1=parseInt(tr1.cells[0].innerHTML); 65 var n2=parseInt(tr2.cells[0].innerHTML); 66 return n1-n2; 67 }) 68 //排序完后,再将排序好的arr[i]appendChild到table中,调整实际显示顺序 69 for (var i = 0; i < arr.length; i++) { 70 //appendChild特点是先将元素从原父级中删除,再将元素添加到新父级元素中 71 tab.tBodies[0].appendChild(arr[i]); 72 } 73 } 74 } 75 </script> 76 </body> 77 </html>