日期:2014-05-16 浏览次数:20527 次
简单且轻松自定义排序规则:
1.initSortTable(asc,desc);是初始化排序预操作(其实就是传入两张图片地址,标识排序方向的)
2.在需要排序的表格table上添加监听事件,sortColumn();此处被我限定click事件作用在th对象上才有效的。
3.需要按列制定排序规则,即在th上添加type类型,例如<th type='string'>1</th>; 如果想要二重排序的话写成<th type='string,0'>1</th>,0标识列号,即本列排序时如果排序内容相同,则按照第零列排序。
4.这里的排序规则可以自由定义,当然目前的代码中只是传入了td单元格内容innerText值,也就是显示的文字。(不过你也可以修改下,传入一个对象)
?
可能文字描述不直观,附上一个例子吧:
<html> <head> <title>sorttest</title> <script type="text/javascript" src="javascript/table-sort.js"></script> </head> <script > function init(){ initSortTable("images/tablesorter/desc.gif","images/tablesorter/asc.gif"); } </script> <body onload='init();'> <table onclick="sortColumn(event)"> <thead> <tr> <th NOWRAP type="Number">ID</th> <th NOWRAP type="myDate,0">Date</th> <th NOWRAP type="str,0">Org</th> <th NOWRAP type="str,0">Dest</th> <th NOWRAP type="bool,0">Flip</th> <th NOWRAP type="ip,0">IP</th> </tr> </thead> <tbody> <tr> <td NOWRAP><%=id %></td> <td nowrap><%=date %></td> <td NOWRAP><%=org %></td> <td NOWRAP><%=dest %></td> <td NOWRAP><%=flip %></td> <td NOWRAP><%=ip %></td> </tr> </tbody> <table> </body> </html>
?
?
具体代码如下,里面包含了一下我自定义处理,比较撮。
var dom = (document.getElementsByTagName) ? true : false; var ie5 = (document.getElementsByTagName && document.all) ? true : false; var arrowUp, arrowDown; var mydefinedChar = "*"; //if (ie5 || dom) //initSortTable(); function initSortTable(asc,desc) { arrowUp = document.createElement("SPAN"); arrowUp.style.display = "inline"; var img = document.createElement("Img"); img.src = asc; arrowUp.appendChild(img); arrowUp.className = "arrow"; arrowDown = document.createElement("SPAN"); arrowDown.style.display = "inline"; img = document.createElement("Img"); img.src = desc; arrowDown.appendChild(img); arrowDown.className = "arrow"; } function sortTable(tableNode, nCol, bDesc, sType) { var tBody = tableNode.tBodies[0]; var trs = tBody.rows; var trl= trs.length; var a = new Array(); for (var i = 0; i < trl; i++) { a[i] = trs[i]; } var start = new Date; window.status = "Sorting data..."; a.sort(compareByColumn(nCol,bDesc,sType)); window.status = "Sorting data done"; for (var i = 0; i < trl; i++) { tBody.appendChild(a[i]); window.status = "Updating row " + (i + 1) + " of " + trl + " (Time spent: " + (new Date - start) + "ms)"; } // check for onsort if (typeof tableNode.onsort == "string") tableNode.onsort = new Function("", tableNode.onsort); if (typeof tableNode.onsort == "function") tableNode.onsort(); } function CaseInsensitiveString(s) { return String(s).toUpperCase(); } function parseDate(s) { return Date.parse(s.replace(/\-/g, '/')); } function toNumber(s) { return Number(s.replace(/[^0-9\.]/g, "")); } function Percent(s) { return Number(s.replace("%", "")); } function dostr(s){ return String(s).toUpperCase(); } function donum(val){ var s1 = ""; var s2 = ""; var s = val; try{ if(val.indexOf("(")!=-1){ s = val.substring(0, val.indexOf("