标签:
所谓表格排序 实际上是 对象数组排序 --> []中的自定义sort函数
参考 http://www.cnblogs.com/xiao-t/archive/2012/12/27/2836248.html
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>table排序</title> </head> <body> <table id="tableTest" width="400" border="1"> <thead> <tr> <td>ID</td> <td>Name</td> <td>col1</td> <td>COL2</td> </tr> </thead> <tbody> <tr> <td>2</td> <td>bbb</td> <td>MANU</td> <td>Znbsp;</td> </tr> <tr> <td>5</td> <td>eee</td> <td>COLS</td> <td>Ssp;</td> </tr> <tr> <td>3</td> <td>ccc</td> <td>KK</td> <td>bsp;</td> </tr> <tr> <td>4</td> <td>ddd</td> <td>Dnbsp;</td> <td>nbsp;</td> </tr> <tr> <td>1</td> <td>aaa</td> <td>Pnbsp;</td> <td>Mnbsp;</td> </tr> </tbody> </table> <input type="button" id="sort" value="表格排序" /> <script> window.onload = function() { var oTable = document.getElementById(‘tableTest‘); var oHead = oTable.tHead; var colHeads = oHead.getElementsByTagName(‘td‘); var oTbody = oTable.tBodies[0]; var oBtn = document.getElementById(‘sort‘); var arr = []; //用来存放每一个tr var isAsc = true; //用来判断升序,还是降序 var colHeadsArr = []; for (var i = 0, len = colHeads.length; i < len; i++) { colHeadsArr.push(colHeads[i]); } //表头事件代理 oHead.addEventListener(‘click‘, function(e) { var target = e.target; if (target.tagName.toLowerCase() === ‘td‘) { var idx = colHeadsArr.indexOf(target); //对第几列进行排序 //和colHeads一样 oTbody.rows只是NodeList不是数组 for (var i = 0; i < oTbody.rows.length; i++) { arr[i] = oTbody.rows[i]; } //此时arr是行构成的数组 arr.sort(function(v1, v2) { if (v1.cells[idx].innerText < v2.cells[idx].innerText) { return -1; } else if (v1.cells[idx].innerText > v2.cells[idx].innerText) { return 1; } else { return 0; } }); for (var j = 0; j < arr.length; j++) { oTbody.appendChild(arr[j]); } } }, false); } </script> </body> </html>
接下来做成插件的样子
标签:
原文地址:http://www.cnblogs.com/cart55free99/p/4489801.html