日期:2014-05-16 浏览次数:20400 次
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>对单列表格进行排序</title> <meta name="generator" content="Studio 3 http://aptana.com/"> <meta name="author" content="Administrator"> <script type="text/javascript" src="js/test3.js"></script> </head> <body> <table border="1" id="tblsort"> <thead> <tr> <th onclick="table.sortTable('tblsort',0)" style="cursor: pointer">Last Name</th> <th onclick="table.sortTable('tblsort',1)" style="cursor: pointer">First Name</th> <th onclick="table.sortTable('tblsort',2,'int')" style="cursor: pointer">Age</th> <th onclick="table.sortTable('tblsort',3,'date')" style="cursor: pointer">Birth Day</th> <th onclick="table.sortTable('tblsort',4,'float')" style="cursor: pointer">Pay</th> </tr> </thead> <tbody> <tr> <td>Adam</td> <td>Jack</td> <td>26</td> <td>1/12/1977</td> <td>3000.12</td> </tr> <tr> <td>Smith</td> <td>Lucy</td> <td>28</td> <td>6/12/1975</td> <td>4000.23</td> </tr> <tr> <td>Johnson</td> <td>Lily</td> <td>35</td> <td>07/12/1965</td> <td>5000.03</td> </tr> <tr> <td>Williams</td> <td>Pual</td> <td>25</td> <td>12/08/1984</td> <td>5000.56</td> </tr> <tr> <td>Gilliam</td> <td>Jack</td> <td>45</td> <td>6/4/1953</td> <td>10000</td> </tr> <tr> <td>Bill</td> <td>Hamson</td> <td>36</td> <td>9/8/1971</td> <td>8000</td> </tr> <tr> <td>Mowen</td> <td>Alex</td> <td>10</td> <td>11/12/2000</td> <td>6000</td> </tr> </tbody> </table> </body> </html>
/** * @author Administrator */ table = { compareTRS : function (otr1, otr2) { var value1 = otr1.cells[0].firstChild.nodeValue; var value2 = otr2.cells[0].firstChild.nodeValue; return value1.localeCompare(value2); }, sortTable : function (tableId,col,datatype) { var otable = document.getElementById(tableId); var tbody = otable.tBodies[0]; var colDataRows = tbody.rows; var trs = []; for (var i=0; i < colDataRows.length; i++) { trs.push(colDataRows[i]); }; if (otable.sortCol == col) { trs.reverse(); } else { trs.sort(table.generateCompareTRS(col, datatype)); } var fragment = document.createDocumentFragment(); for (var i=0; i < trs.length; i++) { fragment.appendChild(trs[i]); }; tbody.appendChild(fragment); otable.sortCol = col; }, generateCompareTRS : function (col, datatype) { return function compareTRS (tr1, tr2) { var value1 = table.convert(tr1.cells[col].firstChild.nodeValue, datatype); var value2 = table.convert(tr2.cells[col].firstChild.nodeValue, datatype); if (value1 < value2) { return -1; } else if (value1 > value2) { return 1; } else { return 0; } } }, convert : function (value, datatype) { switch(datatype) { case "int": return parseInt(value); case "float": return p