实现html中table数据的排序

最近应项目要求,需要对table中的数据进行升序或降序排列,于是研究了一下js,希望对大家有帮助。对了,注意那个innerText和innerHTML
 1 function sortCells(event) {
2 var obj = event.target;
3 var count = 0; count是记录点击次数的,根据奇偶进行升序或降序
4
5 if(!obj.getAttribute("clickCount")){
6 obj.setAttribute("clickCount", 0);
7 } else {
8 count = parseInt(obj.getAttribute("clickCount"));
9 count++;
10 obj.setAttribute("clickCount", count);
11 }
12
13 var table = event.target.parentNode.parentNode;
14 if(table.nodeName.localeCompare("THEAD") == 0){
15 if(table.parentNode.nodeName.localeCompare("TABLE") == 0){
16 table = table.parentNode;
17 } else {
18 return;
19 }
20 } else if(table.nodeName.localeCompare("TBODY") == 0){
21 if(table.parentNode.nodeName.localeCompare("TABLE") == 0){
22 table = table.parentNode;
23 } else {
24 return;
25 }
26 } else if(table.nodeName.localeCompare("TABLE") == 0){
27 } else {
28 return;
29 }
30
31 var colNum;
32 for(x = 0; x < table.rows(1).cells.length; x++){
33 if(event.target.innerText.localeCompare(table.rows(0).cells[x].innerText) == 0){
34 colNum = x;
35 break;
36 }
37 }
38
39 var column = table.rows(1).cells.length;
40 var row = table.rows.length;
41 var Ar = new Array(row - 1);
42 for (x = 0; x < row - 1; x++) {
43 Ar[x] = new Array(column);
44 }
45 for (x = 1; x < row; x++) {
46 for (y = 0; y < column; y++) {
47 Ar[x - 1][y] = table.rows(x).cells(y).innerHTML;
48 }
49 }
50
51      //这个可以对字符串进行本地化排序
52 /* if((count%2) == 0){
53 Ar.sort(function(a, b) {
54 return b[colNum].localeCompare(a[colNum])
55 });
56 } else {
57 Ar.sort(function(a, b) {
58 return a[colNum].localeCompare(b[colNum])
59 });
60 } */
61
62 var temp;
63 for (x = 0; x < row - 1; x++) {
64 for (y = 1; y < row - 1; y++) {
65 temp = Ar[y - 1];
66 if((count % 2) == 0){
67 if (parseInt(Ar[y - 1][colNum]) >= parseInt(Ar[y][colNum])) {
68 Ar[y - 1] = Ar[y];
69 Ar[y] = temp;
70 }
71 } else {
72 if (parseInt(Ar[y - 1][colNum]) <= parseInt(Ar[y][colNum])) {
73 Ar[y - 1] = Ar[y];
74 Ar[y] = temp;
75 }
76 }
77
78 }
79 }
80
81 for (x = 1; x < row; x++) {
82 for (y = 0; y < column; y++) {
83 table.rows(x).cells(y).innerHTML = Ar[x - 1][y];
84 }
85 }
86 count++;
87 }

  

  

转载于:https://www.cnblogs.com/dugujiujian/archive/2011/08/05/2128802.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值