原文地址:javascript 快速隐藏/显示万行表格列的方法

隐藏表格列,最常见的是如下方式:

td.style.display = "none";

这种方式的效率极低。例如,隐藏一个千行表格的某列,在我的笔记本上执行需要约 4000毫秒的时间,令人无法忍受。例如如下代码:

 1 <body>   
 2 <input type=button onclick=hideCol(1) value='隐藏第 2 列'>   
 3 <input type=button onclick=showCol(1) value='显示第 2 列'>   
 4 <div id=tableBox></div>   
 5 <script>     
 6 //--------------------------------------------------------   
 7 // 时间转为时间戳(毫秒)   
 8 function time2stamp() {
 9     var d = new Date();
10     return Date.parse(d) + d.getMilliseconds();
11 }
12 //--------------------------------------------------------   
13 // 创建表格   
14 function createTable(rowsLen) {
15     var str = "<table border=1>" + "<thead>" + "<tr>" + "<th width=100>col1<\/th>" + "<th width=200>col2<\/th>" + "<th width=50>col3<\/th>" + "<\/tr>" + "<\/thead>" + "<tbody>";
16 
17     var arr = [];
18     for (var i = 0; i < rowsLen; i++) {
19         arr[i] = "<tr><td>" + i + "1<\/td><td>" + i + "2</td><td>" + i + "3<\/td></tr>";
20     }
21     str += arr.join("") + "</tbody><\/table>"; // 用 join() 方式快速构建字串,速度极快   
22     tableBox.innerHTML = str; // 生成 table   
23 }
24 //--------------------------------------------------------   
25 // 隐藏/显示指定列   
26 function hideCol(colIdx) {
27     hideOrShowCol(colIdx, 0);
28 }
29 function showCol(colIdx) {
30     hideOrShowCol(colIdx, 1);
31 }
32 // - - - - - - - - - - - - - - - - - - - - - - - - - - - -   
33 function hideOrShowCol(colIdx, isShow) {
34     var t1 = time2stamp(); //    
35     var table = tableBox.children[0];
36     var rowsLen = table.rows.length;
37     var lastTr = table.rows[0];
38     for (var i = 0; i < rowsLen; i++) {
39         var tr = table.rows[i];
40         tr.children[colIdx].style.display = isShow ? "": "none";
41     }
42 
43     var t2 = time2stamp();
44     alert("耗时:" + (t2 - t1) + " 毫秒");
45 }
46 
47 //--------------------------------------------------------   
48 createTable(1000); // 创建千行表格   
49 </script>  
View Code

相关文章:

  • 2022-02-15
  • 2022-12-23
  • 2022-12-23
  • 2019-12-23
  • 2022-12-23
  • 2021-10-05
  • 2021-11-14
  • 2022-12-23
猜你喜欢
  • 2021-12-08
  • 2022-12-23
  • 2021-08-11
  • 2021-12-02
  • 2021-12-12
相关资源
相似解决方案