1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 </head> 7 8 <body> 9 10 11 12 <p>点击按钮,表格 name 字段按字母排序:</p> 13 <p><button onclick="sortTable()">排序</button></p> 14 15 <table border="1" id="myTable"> 16 <tr> 17 <th>Name</th> 18 <th>Country</th> 19 </tr> 20 <tr> 21 <td>Berglunds snabbkop</td> 22 <td>Sweden</td> 23 </tr> 24 <tr> 25 <td>North/South</td> 26 <td>UK</td> 27 </tr> 28 29 <tr> 30 <td>Alfreds Futterkiste</td> 31 32 <td>Germany</td> 33 </tr> 34 <tr> 35 <td>Koniglich Essen</td> 36 <td>Germany</td> 37 </tr> 38 <tr> 39 <td>Magazzini Alimentari Riuniti</td> 40 <td>Italy</td> 41 </tr> 42 <tr> 43 <td>Paris specialites</td> 44 <td>France</td> 45 </tr> 46 <tr> 47 <td>Island Trading</td> 48 <td>UK</td> 49 </tr> 50 <tr> 51 <td>Laughing Bacchus Winecellars</td> 52 <td>Canada</td> 53 </tr> 54 </table> 55 <script> 56 function sortTable() { 57 var table, rows, sw, i, x, y, jh; 58 table = document.getElementById("myTable"); 59 sw = true; 60 //循环是否完成 61 while (sw) { 62 //完成了就不循环了 63 sw = false; 64 //获取行 65 rows = table.getElementsByTagName("TR"); 66 //循环获得每个单元格的内容 67 for (i = 1; i < (rows.length - 1); i++) { 68 //默认不交换 69 jh = false; 70 71 x = rows[i].getElementsByTagName("TD")[0].innerHTML.toLowerCase(); 72 y = rows[i + 1].getElementsByTagName("TD")[0].innerHTML.toLowerCase(); 73 //比较两个单元格的内容 74 if (x > y) { 75 //如果正确肯定要交换位子 76 jh= true; 77 break; 78 } 79 } 80 if (jh) { 81 //互换一下位子 82 rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); 83 sw = true; 84 } 85 } 86 } 87 88 </script> 89 </body> 90 </html>