jquery - 隐藏表列,应用了 colspan ...?

标签 jquery html css css-selectors

我读了很多问题,但都不适合我的情况。 这是我的表结构

enter image description here

如果我想隐藏下面的代码AB 列对我有用。

$('table td:nth-child(1),table th:nth-child(1)').hide();
$('table td:nth-child(2),table th:nth-child(2)').hide();

但是如果我想删除 C 或更高版本的列,它就会给我带来问题。 像下面的代码给了我不相关的输出。

$('table td:nth-child(3),table th:nth-child(3)').hide();

enter image description here

请为此找到 fiddle Link

最佳答案

纯 CSS

这可以通过 CSS 使用 :not() 来完成和 +选择器:

tr :nth-child(3),
tr :nth-child(3):not([colspan]) + :nth-child(4) {
    display: none;
}

JSFiddle demo .

这样做是隐藏第 3 个子元素,然后隐藏第 3 个子元素之前没有 colspan 属性的元素。

在您的表格中,这将隐藏内容为 C34 的单元格。

更新

作为 bolt 时钟 mentioned in comments ,上面的 CSS 将针对在 tr 中找到的任何 :nth-child(n)。为确保这仅针对 tdth 元素,我们可以引入子组合器 (>):

tr > :nth-child(3),
tr > :nth-child(3):not([colspan]) + :nth-child(4) {
    display: none;
}

如果您的 tdth 元素包含它们自己的子元素,您将需要使用它。

jQuery

使用 jQuery,您可以遍历每个 tr 元素,确定第一行匹配的 th 元素是否具有 colspan 属性,然后进行相应处理.在这里,我将其包装在一个名为 hideColumn() 的函数中,该函数接受与您希望隐藏的列相关的 n 参数:

$(function() {
    function hideColumn(n) {
        var headerColSpan = 1;

        $('tr').each(function(i) {
            var nth = $(this).children()[n-1],
                colspan = $(nth).attr('colspan');

            // Pull ColSpan from first row th element
            if (i === 0)
                headerColspan = colspan || 1;

            if (colspan === headerColspan)
                $(nth).hide();
            else
                for (i=0; i < headerColspan; i++) {
                    $($(this).children()[n-1+i]).hide();
                }
        });
    }

    hideColumn(3);
});

JSFiddle demo .

关于jquery - 隐藏表列,应用了 colspan ...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22008618/

相关文章:

jquery - 如何使用 jQuery 为跨度设置值

html - body {位置: relative;}

html - 始终可见的带有列表的菜单组件

javascript - Elfinder如何自定义菜单

javascript - 查找特定值的第一个实例并添加 ID,重复

javascript - jQuery 检查 CSS 宽度是否大于 0 然后添加 CSS 属性

Android HTML5 视频 - 单击播放时有效,但不是 video.play()

javascript - 浏览 DOMString 最简单的方法是什么?

javascript - 在移动 View 中隐藏广告横幅

jquery - 确保函数在 JQuery Widget 中仅绑定(bind)一次