日历归档 |
|
<< < 2024 - 11 > >> | Su | Mo | Tu | We | Th | Fr | Sa | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
|
|
|
About Me |
|
|
ZhangSichu |
|
Male |
|
32 |
|
ZhangSichu@gmail.com |
|
ZhangSichu@hotmail.com |
|
ZhangSichu.com |
|
weibo.com/zhangsichu |
|
|
|
个人推荐 |
|
|
|
|
分类归档 |
|
|
|
|
My Friends |
|
|
|
|
用Javascript对表格排序
|
很多服务器端的Grid控件都支持了排序。当用户单击表头的时候以这个列来排序。但是每次的排序几乎都是发回给服务器在服务器端进行排序。有的是用 Session或ViewState缓存的DataSource用DefautView排序。有的是重新拼SQL的OrderBy排序。这种做法都需要 PostBack,刷新页面,就算用了Ajax,总归需要占用服务器资源。使用Javascript的Array.sort Array.reverse 和DocumentFragment。可以实现Javascript客户端的排序,省去了发回服务器排序的操作。但是如果是很实时的系统可能需要发回到服务器,排序同时刷新数据。
<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>TableSort</title> <script type="text/javascript" language="javascript"> function sortTable(tableID, sortColumn, nodeType) { //get table. var table = document.getElementById(tableID); //get tbody. var tableBody = table.tBodies[0]; //table rows. var tableRows = tableBody.rows; var rowArray = new Array(); //initial row array. for (var i=0; i<tableRows.length; i++) { rowArray[i] = tableRows[i]; } if(table.sortColumn == sortColumn) { rowArray.reverse(); } else { rowArray.sort(generateCompareTR(sortColumn, nodeType)); } var tbodyFragment = document.createDocumentFragment(); for(var i=0; i< rowArray.length; i++) { tbodyFragment.appendChild(rowArray[i]); } tableBody.appendChild(tbodyFragment); table.sortColumn = sortColumn; } function generateCompareTR(sortColumn, nodeType) { return function compareTR(trLeft, trRight){ var leftValue = convert(trLeft.cells[sortColumn].firstChild.nodeValue, nodeType); var rightValue = convert(trRight.cells[sortColumn].firstChild.nodeValue, nodeType); if(leftValue<rightValue) { return -1; } else if(leftValue>rightValue) { return 1; } else { return 0 } } } function convert(value, dataType) { switch(dataType) { case "int": return parseInt(value); case "float": return parseFloat(value); case "date": return new Date(Date.parse(value)); default: return value.toString(); } } </script> </head> <body> <table border="1px" id="tbSort"> <thead> <tr> <th><a href=javascript:sortTable("tbSort",0)>Last Name</a></th> <th><a href=javascript:sortTable("tbSort",1,"int")>Age</a></th> </tr> </thead> <tbody> <tr> <td>Zesson</td><td>23</td> </tr> <tr> <td>Smith</td><td>24</td> </tr> <tr> <td>Henderson</td><td>25</td> </tr> <tr> <td>Williams</td><td>26</td> </tr> <tr> <td>Gilliam</td><td>27</td> </tr> <tr> <td>Walker</td><td>3</td> </tr> <tr> <td>Alex</td><td>20</td> </tr> </tbody> <tfoot> <tr> <td colspan="2">Sum Column.Do not want to sort.</td> </tr> </tfoot> </table> </body> </html>
|
|
|
#re:用Javascript对表格排序 7/9/2007 4:13:21 PM billllll
|
|
|
|
|
|