JS实现的点击表头排序功能示例


Posted in Javascript onMarch 27, 2017

本文实例讲述了JS实现的点击表头排序功能。分享给大家供大家参考,具体如下:

运行效果:

JS实现的点击表头排序功能示例

1、index.html文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>3water.com点击表头排序</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="tablesort.js"></script>
<link type="text/css" rel="StyleSheet" href="tablesort.css" rel="external nofollow" />
<style type="text/css">
body {
 font-family: Verdana, Helvetica, Arial, Sans-Serif;
 font:  Message-Box;
}
code {
 font-size: 1em;
}
</style>
</head>
<body>
<table id="MyHeadTab" cellspacing="0" onclick="sortColumn(event)">
 <thead>
 <tr>
  <td>String</td>
  <td title="CaseInsensitiveString">String</td>
  <td>Number</td>
  <td>Date</td>
  <td>No Sort</td>
 </tr>
 </thead>
  <tbody>
 <tr>
  <td>apple</td>
  <td>Strawberry</td>
  <td>45</td>
  <td>2001-03-13</td>
  <td>Item 0</td>
 </tr>
 <tr>
  <td>Banana</td>
  <td>orange</td>
  <td>7698</td>
  <td>1789-07-14</td>
  <td>Item 1</td>
 </tr>
 <tr>
  <td>orange</td>
  <td>Banana</td>
  <td>4546</td>
  <td>1949-07-04</td>
  <td>Item 2</td>
 </tr>
 <tr>
  <td>Strawberry</td>
  <td>apple</td>
  <td>987</td>
  <td>1975-08-19</td>
  <td>Item 3</td>
 </tr>
 <tr>
  <td>Pear</td>
  <td>blueberry</td>
  <td>98743</td>
  <td>2001-01-01</td>
  <td>Item 4</td>
 </tr>
 <tr>
  <td>blueberry</td>
  <td>Pear</td>
  <td>4</td>
  <td>2001-04-18</td>
  <td>Item 5</td>
 </tr>
  </tbody>
</table>
</body>
</html>

2、tablesort.js文件:

var dom = (document.getElementsByTagName) ? true : false;
var ie5 = (document.getElementsByTagName && document.all) ? true : false;
var arrowUp, arrowDown;
if (ie5 || dom)
 initSortTable();
function initSortTable() {
 arrowUp = document.createElement("SPAN");
 var tn = document.createTextNode("5");
 arrowUp.appendChild(tn);
 arrowUp.className = "arrow";
 arrowDown = document.createElement("SPAN");
 var tn = document.createTextNode("6");
 arrowDown.appendChild(tn);
 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, '/'));
}
/* alternative to number function
 * This one is slower but can handle non numerical characters in
 * the string allow strings like the follow (as well as a lot more)
 * to be used:
 *  "1,000,000"
 *  "1 000 000"
 *  "100cm"
 */
function toNumber(s) {
  return Number(s.replace(/[^0-9/.]/g, ""));
}
function compareByColumn(nCol, bDescending, sType) {
 var c = nCol;
 var d = bDescending;
 var fTypeCast = String;
 if (sType == "Number")
 fTypeCast = Number;
 else if (sType == "Date")
 fTypeCast = parseDate;
 else if (sType == "CaseInsensitiveString")
 fTypeCast = CaseInsensitiveString;
 return function (n1, n2) {
 if (fTypeCast(getInnerText(n1.cells[c])) < fTypeCast(getInnerText(n2.cells[c])))
  return d ? -1 : +1;
 if (fTypeCast(getInnerText(n1.cells[c])) > fTypeCast(getInnerText(n2.cells[c])))
  return d ? +1 : -1;
 return 0;
 };
}
function sortColumnWithHold(e) {
 // find table element
 var el = ie5 ? e.srcElement : e.target;
 var table = getParent(el, "TABLE");
 // backup old cursor and onclick
 var oldCursor = table.style.cursor;
 var oldClick = table.onclick;
 // change cursor and onclick 
 table.style.cursor = "wait";
 table.onclick = null;
 // the event object is destroyed after this thread but we only need
 // the srcElement and/or the target
 var fakeEvent = {srcElement : e.srcElement, target : e.target};
 // call sortColumn in a new thread to allow the ui thread to be updated
 // with the cursor/onclick
 window.setTimeout(function () {
 sortColumn(fakeEvent);
 // once done resore cursor and onclick
 table.style.cursor = oldCursor;
 table.onclick = oldClick;
 }, 100);
}
function sortColumn(e) {
 var tmp = e.target ? e.target : e.srcElement;
 var tHeadParent = getParent(tmp, "THEAD");
 var el = getParent(tmp, "TD");
 if (tHeadParent == null)
 return;
 if (el != null) {
 var p = el.parentNode;
 var i;
 // typecast to Boolean
 el._descending = !Boolean(el._descending);
 if (tHeadParent.arrow != null) {
  if (tHeadParent.arrow.parentNode != el) {
  tHeadParent.arrow.parentNode._descending = null; //reset sort order 
  }
  tHeadParent.arrow.parentNode.removeChild(tHeadParent.arrow);
 }
 if (el._descending)
  tHeadParent.arrow = arrowUp.cloneNode(true);
 else
  tHeadParent.arrow = arrowDown.cloneNode(true);
 el.appendChild(tHeadParent.arrow);
 // get the index of the td
 var cells = p.cells;
 var l = cells.length;
 for (i = 0; i < l; i++) {
  if (cells[i] == el) break;
 }
 var table = getParent(el, "TABLE");
 // can't fail
 sortTable(table,i,el._descending, el.getAttribute("type"));
 }
}
function getInnerText(el) {
 if (ie5) 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 += getInnerText(cs[i]);
  break;
  case 3: //TEXT_NODE
  str += cs[i].nodeValue;
  break;
 }
 }
 return str;
}
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);
}

3、tablesort.css文件:

tr  {background: window;}
td  {color: windowtext; font: menu; padding: 1px; padding-left: 5px; padding-right: 5px;
  border-right: 1px solid buttonshadow;
  border-bottom: 1px solid buttonshadow;
}
table {border-top: 1px solid buttonshadow;
  border-left: 1px solid buttonshadow;
  border-right: 1px solid buttonhighlight;
  border-bottom: 1px solid buttonhighlight;
   }
thead td {background: buttonface; font: menu; border: 1px outset white;
  padding-top: 0; padding: bottom: 0;
  border-top: 1px solid buttonhighlight;
  border-left: 1px solid buttonhighlight;
  border-right: 1px solid buttonshadow;
  border-bottom: 1px solid buttonshadow;
  height: 16px;
}
thead .arrow{font-family: webdings; color: black; padding: 0; font-size: 10px;
  height: 11px; width: 10px; overflow: hidden;
  margin-bottom: 5; margin-top: -3; padding: 0; padding-top: 0; padding-bottom: 2;}
  /*nice vertical positioning :-) */

希望本文所述对大家JavaScript程序设计有所帮助。

Javascript 相关文章推荐
JS的IE和Firefox兼容性集锦
Dec 11 Javascript
dojo学习第一天 Tab选项卡 实现
Aug 28 Javascript
详解AngularJS1.6版本中ui-router路由中/#!/的解决方法
May 22 Javascript
Vue.js结合Ueditor富文本编辑器的实例代码
Jul 11 Javascript
详解如何使用PM2将Node.js的集群变得更加容易
Nov 15 Javascript
浅谈vue.js导入css库(elementUi)的方法
Mar 09 Javascript
Vue.js中的computed工作原理
Mar 22 Javascript
简单实现vue中的依赖收集与响应的方法
Feb 18 Javascript
jquery选择器和属性对象的操作实例分析
Jan 10 jQuery
Vuex的API文档说明详解
Feb 05 Javascript
Vue之封装公用变量以及实现方式
Jul 31 Javascript
create-react-app开发常用配置教程
Jun 25 Javascript
深入理解AngularJS中的ng-bind-html指令
Mar 27 #Javascript
vue2.0实战之基础入门(1)
Mar 27 #Javascript
jQuery中的deferred使用方法
Mar 27 #jQuery
Angular2利用组件与指令实现图片轮播组件
Mar 27 #Javascript
Vue 过渡实现轮播图效果
Mar 27 #Javascript
AngularJS2中一种button切换效果的实现方法(二)
Mar 27 #Javascript
使用AngularJS2中的指令实现按钮的切换效果
Mar 27 #Javascript
You might like
php+dojo 的数据库保存拖动布局的一个方法dojo 这里下载
2007/03/07 PHP
PHP中json_encode、json_decode与serialize、unserialize的性能测试分析
2010/06/09 PHP
PHP实现的比较完善的购物车类
2014/12/02 PHP
php抓取并保存网站图片的实现代码
2015/10/28 PHP
PHP简单操作MongoDB的方法(安装及增删改查)
2016/05/26 PHP
php在windows环境下获得cpu内存实时使用率(推荐)
2018/02/08 PHP
PHP以json或xml格式返回请求数据的方法
2018/05/31 PHP
PHP+redis实现的购物车单例类示例
2019/02/02 PHP
用JS实现的一个include函数
2007/07/21 Javascript
javascript 学习笔记(onchange等)
2010/11/14 Javascript
JS对select控件option选项的增删改查示例代码
2013/10/21 Javascript
js获取html页面节点方法(递归方式)
2013/12/13 Javascript
JavaScript获取当前日期是星期几的方法
2015/04/06 Javascript
手机端页面rem宽度自适应脚本
2015/05/20 Javascript
Jquery幻灯片特效代码分享--打开页面随机选择切换方式(3)
2015/08/15 Javascript
jQuery基于cookie实现的购物车实例分析
2015/12/24 Javascript
js捕捉键盘事件和按键键值的方法
2016/10/10 Javascript
微信小程序实现动态设置页面标题的方法【附源码下载】
2017/11/29 Javascript
JavaScript实现求最大公共子串的方法
2018/02/03 Javascript
[01:05:56]2018DOTA2亚洲邀请赛3月29日 小组赛A组 Newbee VS VG
2018/03/30 DOTA
pycharm 使用心得(一)安装和首次使用
2014/06/05 Python
使用python爬虫实现网络股票信息爬取的demo
2018/01/05 Python
Python中循环后使用list.append()数据被覆盖问题的解决
2018/07/01 Python
基于Python中的yield表达式介绍
2019/11/19 Python
tensorflow常用函数API介绍
2020/04/19 Python
python3.x中安装web.py步骤方法
2020/06/23 Python
《黄河颂》教学反思
2014/02/07 职场文书
竞选学生会主席演讲稿
2014/04/24 职场文书
搞笑的获奖感言
2014/08/16 职场文书
119消防日活动总结
2014/08/29 职场文书
教师党员自我评议不足范文
2014/10/19 职场文书
2014年团队工作总结
2014/11/24 职场文书
CSS实现多个元素在盒子内两端对齐效果
2021/03/30 HTML / CSS
如何解决.cuda()加载用时很长的问题
2021/05/24 Python
MySQL基础快速入门知识总结(附思维导图)
2021/09/25 MySQL
MySQL池化框架学习接池自定义
2022/07/23 MySQL