Discuz教程网

html中table数据排序的js代码

[复制链接]
authicon dly 发表于 2011-9-12 15:04:57 | 显示全部楼层 |阅读模式
对了,注意那个innerText和innerHTML
  1. function sortCells(event) {
  2. var obj = event.target;
  3. var count = 0; count是记录点击次数的,根据奇偶进行升序或降序
  4. if(!obj.getAttribute("clickCount")){
  5. obj.setAttribute("clickCount", 0);
  6. } else {
  7. count = parseInt(obj.getAttribute("clickCount"));
  8. count++;
  9. obj.setAttribute("clickCount", count);
  10. }
  11. var table = event.target.parentNode.parentNode;
  12. if(table.nodeName.localeCompare("THEAD") == 0){
  13. if(table.parentNode.nodeName.localeCompare("TABLE") == 0){
  14. table = table.parentNode;
  15. } else {
  16. return;
  17. }
  18. } else if(table.nodeName.localeCompare("TBODY") == 0){
  19. if(table.parentNode.nodeName.localeCompare("TABLE") == 0){
  20. table = table.parentNode;
  21. } else {
  22. return;
  23. }
  24. } else if(table.nodeName.localeCompare("TABLE") == 0){
  25. } else {
  26. return;
  27. }
  28. var colNum;
  29. for(x = 0; x < table.rows(1).cells.length; x++){
  30. if(event.target.innerText.localeCompare(table.rows(0).cells[x].innerText) == 0){
  31. colNum = x;
  32. break;
  33. }
  34. }
  35. var column = table.rows(1).cells.length;
  36. var row = table.rows.length;
  37. var Ar = new Array(row - 1);
  38. for (x = 0; x < row - 1; x++) {
  39. Ar[x] = new Array(column);
  40. }
  41. for (x = 1; x < row; x++) {
  42. for (y = 0; y < column; y++) {
  43. Ar[x - 1][y] = table.rows(x).cells(y).innerHTML;
  44. }
  45. }
  46.      //这个可以对字符串进行本地化排序
  47. /* if((count%2) == 0){
  48. Ar.sort(function(a, b) {
  49. return b[colNum].localeCompare(a[colNum])
  50. });
  51. } else {
  52. Ar.sort(function(a, b) {
  53. return a[colNum].localeCompare(b[colNum])
  54. });
  55. } */
  56. var temp;
  57. for (x = 0; x < row - 1; x++) {
  58. for (y = 1; y < row - 1; y++) {
  59. temp = Ar[y - 1];
  60. if((count % 2) == 0){
  61. if (parseInt(Ar[y - 1][colNum]) >= parseInt(Ar[y][colNum])) {
  62. Ar[y - 1] = Ar[y];
  63. Ar[y] = temp;
  64. }
  65. } else {
  66. if (parseInt(Ar[y - 1][colNum]) <= parseInt(Ar[y][colNum])) {
  67. Ar[y - 1] = Ar[y];
  68. Ar[y] = temp;
  69. }
  70. }
  71. }
  72. }
  73. for (x = 1; x < row; x++) {
  74. for (y = 0; y < column; y++) {
  75. table.rows(x).cells(y).innerHTML = Ar[x - 1][y];
  76. }
  77. }
  78. count++;
  79. }
复制代码



上一篇:仿jQuery的siblings效果的js代码
下一篇:最常用的12种设计模式小结
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-2 22:04

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表