实现点击表格列实现排序的效果,按照一列一列的排序
代码如下:
1 排序代码 2 3 <!DOCTYPE html> 4 <html lang="en"> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Title</title> 8 <style> 9 table{ 10 border-collapse: collapse; 11 } 12 th,td{ 13 height: 30px; 14 width: 80px; 15 border: 1px solid black; 16 text-align: center; 17 margin: 0; 18 19 } 20 .content{ 21 margin: auto; 22 } 23 </style> 24 </head> 25 <body> 26 <div class="content"> 27 <table> 28 <thead> 29 <tr> 30 <th>姓名</th> 31 <th id="mathBtn">数学</th> 32 <th id="artBtn">语文</th> 33 <th id="EngBtn">英语</th> 34 <th id="allScore">总分</th> 35 </tr> 36 </thead> 37 <tbody> 38 <tr><td>小明</td><td>80</td><td>90</td><td>70</td><td>120</td></tr> 39 <tr><td>小红</td><td>1</td><td>60</td><td>3</td><td>10</td></tr> 40 <tr><td>小刘</td><td>50</td><td>49</td><td>68</td><td>210</td></tr> 41 <tr><td>小张</td><td>20</td><td>30</td><td>40</td><td>100</td></tr> 42 </tbody> 43 </table> 44 </div> 45 <script type="text/javascript"> 46 /* 47 * 48 *,compare比较函数 49 *这里使用匿名函数解决闭包问题 50 * 51 * */ 52 window.onload=function() { 53 var bjuge = false; 54 var body = document.getElementsByTagName("tbody")[0]; 55 var th = document.getElementsByTagName("th");//为什么点击事件没有发生呢 56 for (var k = 1; k < 5; k++) { 57 th[k].onclick =function(k){ 58 return function () { 59 var temp = new Array(4); 60 for (var i = 0; i < 4; i++) { 61 temp[i] = body.children[i].getElementsByTagName("td")[k].innerText; 62 } 63 function compare2(value1, value2) { 64 return value1 - value2; 65 } 66 if (bjuge == true) { 67 temp = temp.sort(compare2); 68 bjuge = false; 69 } else { 70 temp = temp.reverse(temp.sort(compare2)); 71 bjuge = true; 72 } 73 for (var m = 0; m < 4; m++) { 74 for (var j = 0; j < 4; j++) { 75 if (body.children[j].getElementsByTagName("td")[k].innerText == temp[m]) { 76 body.children[m].parentNode.insertBefore(body.children[j], body.children[m]); 77 } 78 } 79 } 80 } 81 }(k) 82 } 83 } 84 </script> 85 </body> 86 </html>
笔记: