用于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 相关文章推荐
给moz-firefox下添加IE方法和属性
Apr 10 Javascript
js 3种归并操作的实例代码
Oct 30 Javascript
js使用split函数按照多个字符对字符串进行分割的方法
Mar 20 Javascript
javascript表格的渲染组件
Jul 03 Javascript
AngularJS使用指令增强标准表单元素功能
Jul 01 Javascript
浅析JavaScript函数的调用模式
Aug 10 Javascript
Javascript循环删除数组中元素的几种方法示例
May 18 Javascript
不得不看之JavaScript构造函数及new运算符
Aug 21 Javascript
AngularJS 实现购物车全选反选功能
Oct 24 Javascript
webpack 代码分离优化快速指北
May 18 Javascript
Vue封装的组件全局注册并引用
Jul 24 Javascript
jquery实现进度条状态展示
Mar 26 jQuery
脚本收藏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递归列出所有文件和目录的代码
2008/09/10 PHP
php数组声明、遍历、数组全局变量使用小结
2013/06/05 PHP
jquery 指南/入门基础
2007/11/30 Javascript
javascript:以前写的xmlhttp池,代码
2008/05/18 Javascript
jQuery实现级联菜单效果(仿淘宝首页菜单动画)
2014/04/10 Javascript
js中直接声明一个对象的方法
2014/08/10 Javascript
javascript 回调函数详解
2014/11/11 Javascript
基于JavaScript实现单选框下拉菜单添加文件效果
2016/06/26 Javascript
js 判断附件后缀的简单实现方法
2016/10/11 Javascript
Easy UI动态树点击文字实现展开关闭功能
2017/09/30 Javascript
react-native fetch的具体使用方法
2017/11/01 Javascript
JS实现简单的星期格式转换功能示例
2018/07/23 Javascript
深入理解JS中Number(),parseInt(),parseFloat()三者比较
2018/08/24 Javascript
在Vue项目中使用jsencrypt.js对数据进行加密传输的方法
2019/04/17 Javascript
vue-router的两种模式的区别
2019/05/30 Javascript
jQuery pager.js 插件动态分页功能实例分析
2019/08/02 jQuery
[01:43]3.19DOTA2发布会 三代刀塔人第三代
2014/03/25 DOTA
[01:55]TI9显影之尘系列 - Evil Geniuses
2019/08/22 DOTA
Python中函数的参数传递与可变长参数介绍
2015/06/30 Python
Python RabbitMQ消息队列实现rpc
2018/05/30 Python
基于Numba提高python运行效率过程解析
2020/03/02 Python
基于Python 的语音重采样函数解析
2020/07/06 Python
python如何导入依赖包
2020/07/13 Python
Django模型验证器介绍与源码分析
2020/09/08 Python
仪器仪表检测毕业生自荐信
2013/10/31 职场文书
应届生幼儿园求职信
2013/11/12 职场文书
爱岗敬业演讲稿范文
2014/01/14 职场文书
电脑专业个人求职信范文
2014/02/04 职场文书
乔迁之喜主持词
2014/03/27 职场文书
活动倡议书范文
2014/05/13 职场文书
师德师风自查总结
2014/10/14 职场文书
公司表扬稿范文
2015/05/05 职场文书
运动会加油稿30字
2015/07/21 职场文书
关于车尾的标语大全
2015/08/11 职场文书
授权协议书范本(3篇)
2019/10/15 职场文书
javascript代码简写的几种常用方式汇总
2021/08/23 Javascript