如果表行直到下一个表头都被隐藏,则隐藏表头



我在一个表中有一个按字母顺序排列的列表。

<tbody>
<tr>
<th><strong>A</strong></th>
</tr>
<tr>
<td class="hide-me">Ants</td>
</tr>
<tr>
<td class="hide-me">Animals</td>
</tr>
<tr>
<td  class="hide-me">Apples</td>
</tr>
<tr>
<th><strong>B</strong></th>
</tr>
<tr>
<td>Bars</td>
</tr>
<tr>
<td class="hide-me">Bats</td>
</tr>
<tr>
<td class="hide-me">Bananas</td>
</tr>
<tr>
<th><strong>C</strong></th>
</tr>
<tr>
<td>Cans</td>
</tr>
<tr>
<td>Cars</td>
</tr>
<tr>
<td>Cats</td>
</tr>
</tbody>

我使用$('table tr:has(td.hide-me)').hide()方法来隐藏任何我不想显示的元素。但是,如果包含普通表格单元格的表格行被隐藏,我也希望能够隐藏表格标题。

在上面的情况下,我想隐藏<tr><th><strong>A</strong></th></tr>,因为它隐藏了下面的所有表行,但没有隐藏<tr><th><strong>B</strong></th></tr>,因为并不是所有的表行都被隐藏。

我对Jquery还比较陌生,不确定如何最好地实现这种情况下的条件语句。

我做的第一件事是在tr上放置一个类,以指示该行包含一个标头。这使得判断哪些行是头更加容易,而不必询问它们是否包含th

我做的第二件事是更改.hide-me的隐藏表达式,先找到隐藏我,然后找到它们的父trs,然后隐藏它们。这样,选择器就不必找到tr并检查每个tr是否都有隐藏我。

最后,逻辑会找到所有的标头,并显示它们,因此,如果之前有任何标头被隐藏,它们将是可见的。然后,它过滤标头,只返回没有任何未隐藏的后续trs的标头。如果标头中没有任何可见的后续trs,则会隐藏它们。

$('.hide-me').closest('tr').hide();
$('.header').show().filter(function(){
return $(this).nextUntil('.header').filter(':not(:hidden)').length < 1;
}).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="header">
<th><strong>A</strong></th>
</tr>
<tr>
<td class="hide-me">Ants</td>
</tr>
<tr>
<td class="hide-me">Animals</td>
</tr>
<tr>
<td class="hide-me">Apples</td>
</tr>
<tr class="header">
<th><strong>B</strong></th>
</tr>
<tr>
<td>Bars</td>
</tr>
<tr>
<td class="hide-me">Bats</td>
</tr>
<tr>
<td class="hide-me">Bananas</td>
</tr>
<tr class="header">
<th><strong>C</strong></th>
</tr>
<tr>
<td>Cans</td>
</tr>
<tr>
<td>Cars</td>
</tr>
<tr>
<td>Cats</td>
</tr>
</tbody>
</table>