隐藏/显示HTML表格中的列 [英] Hide/Show Column in an HTML Table

查看:213
本文介绍了隐藏/显示HTML表格中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多列的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>


推荐答案


这样做,而不需要每个td附加一个类

I would like to do this without attaching a class to every td

就我个人而言,我会选择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表格中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆