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 相关文章推荐
基于jquery+thickbox仿校内登录注册框
Jun 07 Javascript
js自定义事件代码说明
Jan 31 Javascript
浅谈javascript的Touch事件
Sep 27 Javascript
jQuery实现带分组数据的Table表头排序实例分析
Nov 24 Javascript
详解Matlab中 sort 函数用法
Mar 20 Javascript
COM组件中调用JavaScript函数详解及实例
Feb 23 Javascript
JavaScript基于扩展String实现替换字符串中index处字符的方法
Jun 13 Javascript
微信、QQ、微博、Safari中使用js唤起App
Jan 24 Javascript
详解Vue-Router源码分析路由实现原理
May 15 Javascript
JavaScript Date对象功能与用法学习记录
Apr 28 Javascript
Vue 使用typescript如何优雅的调用swagger API
Sep 01 Javascript
移动端JS实现拖拽两种方法解析
Oct 12 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
正则表达式语法
2006/10/09 Javascript
如何利用PHP执行.SQL文件
2013/07/05 PHP
利用PHP如何实现Socket服务器
2015/09/23 PHP
Thinkphp极验滑动验证码实现步骤解析
2020/11/24 PHP
一款JavaScript压缩工具:X2JSCompactor
2007/06/13 Javascript
符合W3C网页标准的iframe标签的使用方法
2007/07/19 Javascript
用js实现下载远程文件并保存在本地的脚本
2008/05/06 Javascript
HTML Dom与Css控制方法
2010/10/25 Javascript
JQuery+JS实现仿百度搜索结果中关键字变色效果
2011/08/02 Javascript
使用jQuery避免鼠标双击的解决方案
2013/08/21 Javascript
jQuery EasyUI datagrid实现本地分页的方法
2015/02/13 Javascript
BootStrap和jQuery相结合实现可编辑表格
2016/04/21 Javascript
微信小程序  网络请求API详解
2016/10/25 Javascript
微信小程序 动态的设置图片的高度和宽度详解及实例代码
2017/02/24 Javascript
jQuery 添加样式属性的优先级别方法(推荐)
2017/06/08 jQuery
Vue单页式应用(Hash模式下)实现微信分享的实例
2017/07/21 Javascript
原生JS实现日历组件的示例代码
2017/09/22 Javascript
jQuery中将json数据显示到页面表格的方法
2018/05/27 jQuery
vue 基于element-ui 分页组件封装的实例代码
2018/12/10 Javascript
使用react context 实现vue插槽slot功能
2019/07/18 Javascript
nodejs文件夹深层复制功能
2019/09/03 NodeJs
基于vue3.0.1beta搭建仿京东的电商H5项目
2020/05/06 Javascript
微信小程序收藏功能的实现代码
2020/06/19 Javascript
[01:14:30]TNC vs VG 2019国际邀请赛淘汰赛 胜者组赛BO3 第二场 8.20.mp4
2019/08/22 DOTA
[42:24]完美世界DOTA2联赛PWL S2 LBZS vs FTD.C 第三场 11.27
2020/12/01 DOTA
一步步解析Python斗牛游戏的概率
2016/02/12 Python
举例讲解Python中metaclass元类的创建与使用
2016/06/30 Python
在python中按照特定顺序访问字典的方法详解
2018/12/14 Python
softmax及python实现过程解析
2019/09/30 Python
pytorch中交叉熵损失(nn.CrossEntropyLoss())的计算过程详解
2020/01/02 Python
python实现低通滤波器代码
2020/02/26 Python
使用CSS3创建动态菜单效果
2015/07/10 HTML / CSS
法国设计制造的扫帚和刷子:Andrée Jardin
2018/12/06 全球购物
计划生育宣传标语
2014/06/21 职场文书
社区党风廉政建设调研报告
2015/01/01 职场文书
css实现两栏布局,左侧固定宽,右侧自适应的多种方法
2021/08/07 HTML / CSS