隐藏/显示列

2024-01-02

在html中,是否可以显示/隐藏列?

例如我们有一个这样的表:

ID    Color    Number 
1    #990000    C001
2    #009900    C002
3    #FFFFFF    C003
4    #000000    C004

代码如下:

<table>
    <tr>
        <th class="Title">ID</th>
        <th class="Title">Color</th>
        <th class="Title">Number</th>
    </tr>
    <tr>
        <td>1</td>
        <td>#990000</td>
        <td>C001</td>
    </tr>
    <tr>
        <td>2</td>
        <td>#009900</td>
        <td>C002</td>
    </tr>
    <tr>
        <td>3</td>
        <td>#FFFFFF</td>
        <td>C003</td>
    </tr>
    <tr>
        <td>4</td>
        <td>#000000</td>
        <td>C004</td>
    </tr>
</table>

如何为每列添加一个按钮(或其他内容)以便隐藏/显示该列?我无法向 TD 添加课程。这在 jquery 中可能吗?


好吧,首先,由于表格是由带有单元格的行构造的,为了选择您需要使用的整列:nth-of-type所有行上的选择器一起单独选择它们的单元格。

$('table td:nth-of-type(1),table th:nth-of-type(1)');

请注意,我们选择两者<td> and <th>也可以选择标题。

现在,如果您只需要隐藏功能,您确实可以向每一列添加一个按钮以用于隐藏目的:

$(function () {
    $('table th').each(function () {
        $('<button>Hide</button>').appendTo($(this)).click(function () {
            var column_index = $(this).parent().index()+1;
            $('table td:nth-of-type('+column_index+'),table th:nth-of-type('+column_index+')').hide();
        });
    });

});

Example 1 http://jsfiddle.net/TheBanana/StLuX/

但是,如果您需要再次显示列,则需要单独放置按钮,否则它们将与列一起消失。

例如,您可以放置​​一个文本框,在其中指定要隐藏/显示的列的索引,如下所示:

添加到html:

<input id="col_hide" placeholder="insert col index 1+"></input>
<input type="submit" id="bt_hide" value="hide/show" />

js:

$(function () {
    $('#bt_hide').click(function () {
        var column_index = $('#col_hide').val();
        $('table td:nth-of-type(' + column_index + '),table th:nth-of-type(' + column_index + ')').toggle();
    });
});

Example 2 http://jsfiddle.net/TheBanana/wp86V/

或者,如果您希望表格更加用户友好,您可以在表格外的每列创建一个按钮:

js:

$(function () {
    $('table th').each(function (_id, _value) {
        $('<button>Toggle ' + parseInt(_id + 1) + '</button>').appendTo($("#togglers")).click(function (e) {
            $('table td:nth-of-type(' +  parseInt(_id + 1) + '),table th:nth-of-type(' +  parseInt(_id + 1) + ')').toggle();
            e.preventDefault();
        });
    });

});

Example 3 http://jsfiddle.net/TheBanana/u6P6M/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

隐藏/显示列 的相关文章

随机推荐