【问题标题】:Hide parent thead if ALL tr in tbody are hidden display:none如果 tbody 中的所有 tr 都被隐藏,则隐藏父 thead display:none
【发布时间】:2015-03-08 18:21:48
【问题描述】:

我需要你的帮助:

问题:

我的表格有一个选择过滤器。 如果值不同,过滤器会隐藏 tbody 的 tr 行。表头仍然显示。

问题:

如果选择过滤器隐藏 (display:none; ?) tbody 的所有 tr,thead 也应该隐藏。

代码:

$(document).ready(function(){
    $("select[name='kurs']").click(function() {
        $('tbody').each(function(){
            if ($(this).find("tr:hidden")) {
                $(this).closest(thead).hide();
            }
        });
    });
});

【问题讨论】:

  • 如果没有tr可见,隐藏整个表格不是更容易吗?
  • @RoryMcCrossan 表中可能不止一个tbody
  • @Teemu:即便如此,如果它们都被隐藏了,那么隐藏 thead 和整个 table 并没有太大区别,除非有一个 tfoot 不应该隐藏原因(可能不太可能)。
  • 嗨! thead 或完整的整个表 - 两者都可以。

标签: javascript jquery filter


【解决方案1】:

这也可以:

$(this).parent().find("thead").hide();

示例代码:

function hide() {

$('tbody').each(function(){  
  if($(this).not("tr:hidden").length=1)
    {      
      $(this).parent().find("thead").hide();
    }
});
  
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Table
<table border='1'>
<thead>  
  <tr><td>H1</td><td>H2</td></tr>
</thead>
<tbody>
  <tr style='display:none'><td>a</td><td>b</td></tr>
  <tr style='display:none'><td>a</td><td>b</td></tr>
  <tr style='display:none'><td>a</td><td>b</td></tr>
  <tr style='display:none'><td>a</td><td>b</td></tr>
 </tbody>
</table>
<button onClick='hide()'>Hide</button>

【讨论】:

  • 这段代码杀死了所有的线索。我在一页上有 4 个不同的表。此外,只有 1 个隐藏 tr 的 tbody 也松开了头。
【解决方案2】:

怎么样

$('tbody').each(function(){
    if ($(this).has("> tr:visible").length === 0){
        $(this).closest('table').hide();
    }
});

它检查tbody 中可见的trs,如果没有,则隐藏table

【讨论】:

  • 我没有意识到.has() 没有返回布尔结果。
【解决方案3】:

查看fiddle 看看是否是您想要的。

When the select changes, it filters the rows.我做了一些可能会或可能不会像您可能拥有的过滤方法的事情。重要的是在没有行时关闭标题的部分。

$("#filter").change(function () {// Select changes and filters rows of the different tables.
    var class_to_filter = "." + $(this).val();// I'm accessing rows by class in order to close them, you may access them using some other method.

    $.each($(class_to_filter), function (i, item) {// For each one of them, close and check if you have to close thead as well.
        var $tr = $(item).closest('tr'),
            $tbody = $tr.closest('tbody'),
            $thead = $tbody.siblings('thead'),
            numOfVisibleRows;

        $tr.hide();// Hide row.
        numOfVisibleRows = $('tr:visible', $tbody).length;// Number of sibling rows visible.

        if (!numOfVisibleRows) {// if 0, hide thead.
            $thead.hide();
        }
    });
});

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    相关资源
    最近更新 更多