作家
登录

JavaScript高级程序设计 阅读笔记(十九) js表格排序

作者: 来源:www.28hudong.com 2013-03-30 00:24:42 阅读 我要评论

排序代码 复制代码 代码如下: function SortTable(sTableID, iCol, sDataType){ this.oTable=document.getElementById(sTableID); this.oTBody=this.oTable.tBodies[0]; this.colDataRows=this.oTBody.rows; this.aTRs=[]; this.iCol=iCol; this.sDataType=sDataType; } SortTable.prototype={ convert:function(sValue, sDataType){ switch(sDataType){ case "int": return parseInt(sValue); case "float": return parseFloat(sValue); case "date": return new Date(sValue); default: return sValue.toString(); } }, generateCompareTRs:function(iCol, sDataType, that){ return function compareTRs(oTR1,oTR2){ var vValue1= that.convert(oTR1.cells[iCol].firstChild.nodeValue, sDataType), vValue2= that.convert(oTR2.cells[iCol].firstChild.nodeValue, sDataType); if(vValue1 < vValue2){ return -1; } else if(vValue1 > vValue2){ return 1; } else{ return 0; } }; }, sort:function(){ for(var i=0,l=this.colDataRows.length;i<l;i++){ this.aTRs.push(this.colDataRows[i]); } if(this.oTable.sortCol === this.iCol){ this.aTRs.reverse(); } else { this.aTRs.sort(this.generateCompareTRs(this.iCol, this.sDataType, this)); } var oFragment=document.createDocumentFragment(); for(var i=0,l=this.aTRs.length;i<l;i++){ oFragment.appendChild(this.aTRs[i]); } this.oTBody.appendChild(oFragment); this.oTable.sortCol = this.iCol; } } 调用示例 复制代码 代码如下: function bindSortTable(sTableID, iCol, sDataType){ var table=document.getElementById(sTableID), ftr=table.tHead.rows[0], tds=ftr.cells; if(tds[iCol]){ tds[iCol].onclick=function(){ var sortTable=new SortTable(sTableID, iCol, sDataType); sortTable.sort(); } } } window.onload=function(){ bindSortTable("tblSort",0); bindSortTable("tblSort",1); bindSortTable("tblSort",2,"int"); bindSortTable("tblSort",3,"float"); bindSortTable("tblSort",4,"date"); } 完整Demo: JSCode demo table{ border-collapse:collapse; } table thead tr{ cursor:pointer; background:#EEE; } td{ border:1px solid #CCC; padding:10px; } Last Name First Name Number Score Birthday O D 5 20.1 7/12/1999 P C 3 30.1 7/12/1990 Q B 4 27.1 7/12/1995 R A 2 24.1 7/12/1998 [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] 作者:Artwl 出处:http://artwl.cnblogs.com

  推荐阅读

  jquery 插件学习(三)

例如: 复制代码 代码如下: $(this).test().hide().height(); 要实现类似的连写行为,就应该在每个插件方法中,返回一个jquery对象,除非方法需要明确返回值。返回的jquery对象通常就是this所引用的对象。如果使用>>>详细阅读


本文标题:JavaScript高级程序设计 阅读笔记(十九) js表格排序

地址:http://www.17bianji.com/kaifa2/JS/23181.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)