我想显示一个基本的HTML表格,并带有控件以切换显示/隐藏其他列:
<table id="mytable">
<tr>
<th>Column 1</th>
<th class="col1">1a</th>
<th class="col1">1b</th>
<th>Column 2</th>
<th class="col2">2a</th>
<th class="col2">2b</th>
</tr>
<tr>
<td>100</td>
<td class="col1">40</td>
<td class="col1">60</td>
<td>200</td>
<td class="col2">110</td>
<td class="col2">90</td>
</tr>
</table>
因此,默认情况下只显示列1和列2-但是当您单击列1时,我希望1a和1b进行切换,列2与2a和2b进行相同的操作。 我可能最终会有更多的列和大量的行-因此,当我测试时,任何JavaScript循环方法都太慢无法使用。
唯一看起来足够快速的方法是设置类似于这样的css:
table.hide1 .col1 { display: none; }
table.hide2 .col2 { display: none; }
table.hide3 .col3 { display: none; }
table.show1 .col1 { display: table-cell; }
table.show2 .col2 { display: table-cell; }
table.show3 .col3 { display: table-cell; }
然后在表头单元格上设置 onClick 函数调用,以触发切换 - 并确定要设置 "mytable" 的哪个 CSS 类来创建我正在寻找的切换效果。是否有一种简单的方法来设置这个,使得代码可以适用于 n#列?
更新
这是我想出的解决方案,运行得非常好 - 而且非常快。如果你能想到改进的方法,请告诉我。
CSS
.col1 {display: none; }
.col2 {display: none; }
.col3 {display: none; }
table.show1 .col1 { display: table-cell; }
table.show2 .col2 { display: table-cell; }
table.show3 .col3 { display: table-cell; }
JavaScript
function toggleColumn(n) {
var currentClass = document.getElementById("mytable").className;
if (currentClass.indexOf("show"+n) != -1) {
document.getElementById("mytable").className = currentClass.replace("show"+n, "");
}
else {
document.getElementById("mytable").className += " " + "show"+n;
}
}
并且HTML片段:
<table id="mytable">
<tr>
<th onclick="toggleColumn(1)">Col 1 = A + B + C</th>
<th class="col1">A</th>
<th class="col1">B</th>
<th class="col1">C</th>
<th onclick="toggleColumn(2)">Col 2 = D + E + F</th>
<th class="col2">D</th>
<th class="col2">E</th>
<th class="col2">F</th>
<th onclick="toggleColumn(3)">Col 3 = G + H + I</th>
<th class="col3">G</th>
<th class="col3">H</th>
<th class="col3">I</th>
</tr>
<tr>
<td>20</td>
<td class="col1">10</td>
<td class="col1">10</td>
<td class="col1">0</td>
<td>20</td>
<td class="col2">10</td>
<td class="col2">8</td>
<td class="col2">2</td>
<td>20</td>
<td class="col3">10</td>
<td class="col3">8</td>
<td class="col3">2</td>
</tr>
</table>
table.className= 'show1 show3'
等。我怀疑IE的问题是,正如我所提到的,它不支持display: table-cell
。我会使用类似于hide
的类,而不是show
,这样您只需要声明table.hide1 col1 { display: none; }
。 - bobince