问题描述
我有一个包含多列的 HTML 表,我需要使用 jquery 实现一个列选择器.当用户单击复选框时,我想隐藏/显示表格中的相应列.我想在不将类附加到表中的每个 td 的情况下执行此操作,有没有办法使用 jquery 选择整个列?下面是一个 HTML 示例.
I have an HTML table with several columns and I need to implement a column chooser using jquery. When a user clicks on a checkbox I want to hide/show the corresponding column in the table. I would like to do this without attaching a class to every td in the table, is there a way to select an entire column using jquery? Below is an example of the HTML.
<table>
<thead>
<tr><th class="col1">Header 1</th><th class="col2">Header 2</th><th class="col3">Header 3</th></tr>
</thead>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>
<form>
<input type="checkbox" name="col1" checked="checked" /> Hide/Show Column 1 <br />
<input type="checkbox" name="col2" checked="checked" /> Hide/Show Column 2 <br />
<input type="checkbox" name="col3" checked="checked" /> Hide/Show Column 3 <br />
</form>
推荐答案
就我个人而言,我会采用 class-on-each-td/th/col 方法.然后,您可以使用对容器上的 className 的单个写入来打开和关闭列,假设样式规则如下:
Personally, I would go with the the class-on-each-td/th/col approach. Then you can switch columns on and off using a single write to className on the container, assuming style rules like:
table.hide1 .col1 { display: none; }
table.hide2 .col2 { display: none; }
...
这将比任何 JS 循环方法都快;对于非常长的表,它会对响应速度产生重大影响.
This is going to be faster than any JS loop approach; for really long tables it can make a significant difference to responsiveness.
如果您可以不支持 IE6,则可以使用邻接选择器来避免将类属性添加到 tds.或者,如果您关心的是使标记更清晰,您可以在初始化步骤中从 JavaScript 自动添加它们.
If you can get away with not supporting IE6, you could use adjacency selectors to avoid having to add the class attributes to tds. Or alternatively, if your concern is making the markup cleaner, you could add them from JavaScript automatically in an initialisation step.
这篇关于隐藏/显示 HTML 表格中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!