用于table内容排序


Posted in Javascript onJuly 21, 2006

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>sort table</title>
<style type="text/css">
a {
 color:#000000;
 font-weight: bold;
 text-decoration: none;
}
</style>
<SCRIPT src="sorttable.js"></SCRIPT>
</head>
<body>
<p>点击标题排序</p>
<table width="481" border="1" cellpadding="0" cellspacing="3" id="mytable" class="sortable">
  <tbody>
    <tr>
      <th width="165">Name</th>
      <th width="101">Salary</th>
      <th width="101" align="center">Extension</th>
      <th width="99" align="center">Start date</th>
    </tr>
    <tr>
      <td>Bloggs, Fred</td>
      <td>$12000.00</td>
      <td align="center">1353</td>
      <td align="center">18/08/2003</td>
    </tr>
    <tr>
      <td>Turvey, Kevin</td>
      <td>$191200.00</td>
      <td align="center">2342</td>
      <td align="center">02/05/1979</td>
    </tr>
    <tr>
      <td>Mbogo, Arnold</td>
      <td>$32010.12</td>
      <td align="center">2755</td>
      <td align="center">09/08/1998</td>
    </tr>
    <tr>
      <td>Shakespeare, Bill</td>
      <td>$122000.00</td>
      <td align="center">3211</td>
      <td align="center">12/11/1961</td>
    </tr>
    <tr>
      <td>Shakespeare, Hamnet</td>
      <td>$9000</td>
      <td align="center">9005</td>
      <td align="center">01/01/2002</td>
    </tr>
    <tr>
      <td>Fitz, Marvin</td>
      <td>$3300</td>
      <td align="center">5554</td>
      <td align="center">22/05/1995</td>
    </tr>
  </tbody>
</table>
<p><a href="http://www.flaspx.com/weblog" target="_blank">Alpha's blog</a></p>
</body>
</html>

addEvent(window, "load", sortables_init);
var SORT_COLUMN_INDEX;
function sortables_init() {
    // Find all tables with class sortable and make them sortable
    if (!document.getElementsByTagName) return;
    tbls = document.getElementsByTagName("table");
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
        if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
            //initTable(thisTbl.id);
            ts_makeSortable(thisTbl);
        }
    }
}
function ts_makeSortable(table) {
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    if (!firstRow) return;
    // We have a first row: assume it's the header, and make its contents clickable links
    for (var i=0;i<firstRow.cells.length;i++) {
        var cell = firstRow.cells[i];
        var txt = ts_getInnerText(cell);
        cell.innerHTML = '<a href="#" class="sortheader" '+ 
        'onclick="ts_resortTable(this, '+i+');return false;">' + 
        txt+'<span class="sortarrow"></span></a>';
    }
}
function ts_getInnerText(el) {
 if (typeof el == "string") return el;
 if (typeof el == "undefined") { return el };
 if (el.innerText) return el.innerText; //Not needed but it is faster
 var str = "";
 var cs = el.childNodes;
 var l = cs.length;
 for (var i = 0; i < l; i++) {
  switch (cs[i].nodeType) {
   case 1: //ELEMENT_NODE
    str += ts_getInnerText(cs[i]);
    break;
   case 3: //TEXT_NODE
    str += cs[i].nodeValue;
    break;
  }
 }
 return str;
}
function ts_resortTable(lnk,clid) {
    // get the span
    var span;
    for (var ci=0;ci<lnk.childNodes.length;ci++) {
        if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
    }
    var spantext = ts_getInnerText(span);
    var td = lnk.parentNode;
    var column = clid || td.cellIndex;
    var table = getParent(td,'TABLE');
    // Work out a type for the column
    if (table.rows.length <= 1) return;
    var itm = ts_getInnerText(table.rows[1].cells[column]);
    sortfn = ts_sort_caseinsensitive;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^[$]/)) sortfn = ts_sort_currency;
    if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
    SORT_COLUMN_INDEX = column;
    var firstRow = new Array();
    var newRows = new Array();
    for (i=0;i<table.rows[0].length;i++) { firstRow[i] = table.rows[0][i]; }
    for (j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }
    newRows.sort(sortfn);
    if (span.getAttribute("sortdir") == 'down') {
        ARROW = '↑';
        newRows.reverse();
        span.setAttribute('sortdir','up');
    } else {
        ARROW = '↓';
        span.setAttribute('sortdir','down');
    }
    // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
    // don't do sortbottom rows
    for (i=0;i<newRows.length;i++) { if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);}
    // do sortbottom rows only
    for (i=0;i<newRows.length;i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);}
    // Delete any other arrows there may be showing
    var allspans = document.getElementsByTagName("span");
    for (var ci=0;ci<allspans.length;ci++) {
        if (allspans[ci].className == 'sortarrow') {
            if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
                allspans[ci].innerHTML = '';
            }
        }
    }
    span.innerHTML = ARROW;
}
function getParent(el, pTagName) {
 if (el == null) return null;
 else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) // Gecko bug, supposed to be uppercase
  return el;
 else
  return getParent(el.parentNode, pTagName);
}
function ts_sort_date(a,b) {
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa.length == 10) {
        dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
    } else {
        yr = aa.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
    }
    if (bb.length == 10) {
        dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
    } else {
        yr = bb.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
    }
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
}
function ts_sort_currency(a,b) { 
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    return parseFloat(aa) - parseFloat(bb);
}
function ts_sort_numeric(a,b) { 
    aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX])); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
}
function ts_sort_caseinsensitive(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}
function ts_sort_default(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}
Javascript 相关文章推荐
JavaScript中的Screen屏幕对象
Jan 16 Javascript
jQuery使用toggleClass方法动态添加删除Class样式的方法
Mar 26 Javascript
jQuery中extend()和fn.extend()方法详解
Jun 03 Javascript
javascript设计模式之单体模式学习笔记
Feb 15 Javascript
jQuery实现弹窗居中效果类似alert()
Feb 27 Javascript
JS实现简易刻度时钟示例代码
Mar 11 Javascript
常见的浏览器Hack技巧整理
Jun 29 Javascript
JS路由跳转的简单实现代码
Sep 21 Javascript
详谈js中标准for循环与foreach(for in)的区别
Nov 02 Javascript
深入浅析Vue全局组件与局部组件的区别
Jun 15 Javascript
jQuery对底部导航进行跳转并高亮显示的实例代码
Apr 23 jQuery
javascript中this的用法实践分析
Jul 29 Javascript
脚本收藏iframe
Jul 21 #Javascript
document.all还是document.getElementsByName?
Jul 21 #Javascript
关于IFRAME 自适应高度的研究
Jul 20 #Javascript
怎么用javascript进行拖拽
Jul 20 #Javascript
繁简字转换功能
Jul 19 #Javascript
Javascript - HTML的request类
Jul 15 #Javascript
表单的一些基本用法与技巧
Jul 15 #Javascript
You might like
让php处理图片变得简单 基于gb库的图片处理类附实例代码下载
2011/05/17 PHP
php htmlspecialchars()与shtmlspecialchars()函数的深入分析
2013/06/05 PHP
5种PHP创建数组的实例代码分享
2014/01/17 PHP
ThinkPHP的截取字符串函数无法显示省略号的解决方法
2014/06/25 PHP
PHP实现的一致性Hash算法详解【分布式算法】
2018/03/31 PHP
php设计模式之抽象工厂模式分析【星际争霸游戏案例】
2020/01/23 PHP
身份证号码前六位所代表的省,市,区, 以及地区编码下载
2007/04/12 Javascript
JavaScript 字符编码规则
2009/05/04 Javascript
jQuery图片滚动图片的效果(另类实现)
2013/06/02 Javascript
JavaScript中实现最高效的数组乱序方法
2014/10/11 Javascript
JavaScript ParseFloat()方法
2015/12/18 Javascript
vue.js2.0点击获取自己的属性和jquery方法
2018/02/23 jQuery
js jquery 获取某一元素到浏览器顶端的距离实现方法
2018/09/05 jQuery
js实现轮播图特效
2020/05/28 Javascript
[37:02]OG vs INfamous 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
初学python数组的处理代码
2011/01/04 Python
Python标准库之collections包的使用教程
2017/04/27 Python
python thrift搭建服务端和客户端测试程序
2018/01/17 Python
Python爬虫实现百度图片自动下载
2018/02/04 Python
Python之文字转图片方法
2018/05/10 Python
python实现自主查询实时天气
2018/06/22 Python
攻击者是如何将PHP Phar包伪装成图像以绕过文件类型检测的(推荐)
2018/10/11 Python
详解python中sort排序使用
2019/03/23 Python
手把手教你进行Python虚拟环境配置教程
2020/02/03 Python
德国大型的家具商店:Pharao24.de
2016/10/02 全球购物
日本食品网上商店:JaponShop.com
2017/11/28 全球购物
英国休闲奢华的缩影:Crew Clothing
2019/05/05 全球购物
MYPROTEIN澳大利亚官方网站:欧洲运动营养品牌
2019/06/26 全球购物
金讯Java笔试题目
2013/06/18 面试题
跟单文员的岗位职责
2013/11/14 职场文书
《走一步再走一步》教学反思
2014/02/15 职场文书
高二学生评语大全
2014/04/25 职场文书
村主任“四风”问题个人对照检查材料思想汇报
2014/10/02 职场文书
党性分析材料格式
2014/12/19 职场文书
2015年公司保安年终工作总结
2015/05/14 职场文书
MySQL磁盘碎片整理实例演示
2022/04/03 MySQL