【问题标题】:Hide table column, which applied colspan...?隐藏表格列,其中应用了 colspan ...?
【发布时间】:2014-02-26 16:28:48
【问题描述】:

我阅读了很多问题,但与我的情况不符。 这是我的表结构

如果我想隐藏代码下面的列 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();

请为此Link寻找小提琴

【问题讨论】:

  • 你能做个小提琴吗?
  • 当然。您正在删除第三个孩子 - 在中间列,您还需要删除第四个孩子。
  • 第三个你也需要隐藏第四个
  • 如果您知道需要隐藏哪些列,如何将特定的 CSS 类添加到要隐藏的列并使用 $('.toggle-column1').toggle(); 显示/隐藏这些?
  • 查看带有两个可切换列组的示例小提琴(刚刚更新):jsfiddle.net/Moonbird_IT/g2rym/1

标签: jquery html css css-selectors


【解决方案1】:

纯 CSS

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

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

JSFiddle demo.

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

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

更新

作为 BoltClock 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 来应用它吗?
  • @Deer 我已经为我的答案添加了一个 jQuery 解决方案。
  • 期待一些简洁的jquery,但我认为必须编写这么多行代码。谢谢
  • 它不适用于 hideColumn(5);等有任何更新让我知道。
  • @Deer 您的要求与您最初提出的要求有很大不同。我最初的 CSS 解决方案回答了您最初提出的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
  • 2012-01-04
  • 1970-01-01
相关资源
最近更新 更多