用于table内容排序

<!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");
  }
}

(0)

相关推荐

  • 用于table内容排序

    <!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-Typ

  • jquery对table做排序操作的实例演示

    最近要对报表数组进行排序,在前端处理如下: 首先在前台页面加载时对每行tr添加自定义的属性data-sort-field-ftime,属性值为要排序的字段的值(我的是数字比较方便): $.each(jsonarray, function(i, obj) { troptions += "<tr data-sort-field-ftime=\""+obj.paiming+"\">"; troptions += "<td&g

  • Angular实现的table表格排序功能完整示例

    本文实例讲述了Angular实现的table表格排序功能.分享给大家供大家参考,具体如下: 先来看看效果图: 完整代码如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>www.jb51.net Angular表格排序</title> <style> table{ border: 1px solid; text-align:

  • jQuery实现带分组数据的Table表头排序实例分析

    本文实例讲述了jQuery实现带分组数据的Table表头排序.分享给大家供大家参考,具体如下: 如下图: 要求:点击表头排序时,"分组"及"分组明细"的数据层次关系不变 从网上找了一段常规的table排序,改了改,以满足"分组支持",贴在这里备份 <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/T

  • 将页面table内容与样式另存成excel文件的方法

    在项目做完之余,测试最近做的一个论坛,其中有个导出功能,发现点击网页导出按钮之后,将页面的table内容另存为excel文件后,却发现无法保存表格样式,经过问题分析之后找到根本原因,下面小编就把我的实现思路给大家分享如下: 问题描述: 问题分析过程: 1.table表格用class,而不是style.导出时并没有导出class定义,若换成style,将颜色样式直接写在style中,就会导出样式. style是样式,在HTML中用这个来标明属性样式,是css中的内容,而class是类,申明和定义里

  • vue excel上传预览和table内容下载到excel文件中

    excel上传预览 这里会用到 npm i element-ui npm i xlsx 在vue的template中写上,排版和css看个人需求 <div> 选择文件 <input type="file" d="file_input" @change="importf(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadshe

  • 分享一个自己写的table表格排序js插件(高效简洁)

    像:jQuery的table排序插件(感觉其使用比较麻烦或不清楚其具体用法,就没有使用).原生态js的table排序插件等,最后比较看了下--采用了一个原生态js的table排序插件,并在其基础上做了些修改,虽有些勉强或有些地方使用不太舒服,但最算是比较好的实现了当时需要的功能.而前两天,对原有表格做了点儿修改--增加隔行换色的功能,问题就出现了,--效果错乱:检查分析了下,问题出在其table排序插件代码上--其原代码写的比较难理解,修改还不如重新自己写一个table排序插件. 说写就写,ta

  • html中table数据排序的js代码

    对了,注意那个innerText和innerHTML 复制代码 代码如下: function sortCells(event) { var obj = event.target; var count = 0; count是记录点击次数的,根据奇偶进行升序或降序 if(!obj.getAttribute("clickCount")){ obj.setAttribute("clickCount", 0); } else { count = parseInt(obj.ge

  • 页面内容排序插件jSort使用方法

    当页面列表内容很多的时候,我们可能需要将内容按照某个方式进行排序,比如按照字母或者大小等排序.本文将使用排序插件jSort来对页面内容进行排序. jSort插件可以对页面任何内容进行排序(tables, lists, div elements),跨浏览器兼容且非常轻巧. 运行效果图: XHTML 首先在head部分引入jquery库和jSort插件. <script type="text/javascript" src="http://ajax.googleapis.c

  • 读取table内容的javascript代码

    222222 我们 www.jb51.net 百度 www.baidu.com 服务器软件 s.jb51.net //使用数组取得表格值 function getRowText() { var arr = new Array(); var count = 0; for(var i=0;i [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] 定义和用法 rows 集合返回表格中所有行(TableRow 对象)的一个数组,即一个 HTMLCollection. 该集合包括 <thead>.

随机推荐