问题:我需要一种在 jQuery 中隐藏父 div 的方法,如果该 div 中包含的列表中的所有子项都被隐藏的话。
上下文:我正在开发一个允许管理员上传 PDF 的员工门户。当他们上传 PDF 时,他们可以将其附加到一个类别,还可以为其添加标签。标签的目的是用于内联过滤功能,如果他们从菜单中选择特定标签,则只显示与特定标签关联的文件。我的标记的一个简化示例:
<!-- Filtering Menu -->
<ul class="resource-filters">
<li class="all">All</li>
<li class="filter-example">Filter #1</li>
<li class="filter-example">Filter #2</li>
<li class="filter-example">Filter #3</li>
</ul>
<!-- Category #1 -->
<div class="resources-files-container">
<h3>Category #1</h3>
<ul class="attachment-list">
<li class="filter-example-1">
<a href="#">PDF Example #1</a>
</li>
<li class="filter-example-3">
<a href="#">PDF Example #3</a>
</li>
</ul>
</div>
<!-- Category #2 -->
<div class="resources-files-container">
<h3>Category #2</h3>
<ul class="attachment-list">
<li class="filter-example-2 hidden">
<a href="#">PDF Example #2</a>
</li>
<li class="filter-example-2 hidden">
<a href="#">PDF Example #2</a>
</li>
</ul>
</div>
我遇到的问题是,假设我从菜单中选择“Filter #1”。所有不具有 .filter-example-1
类的列表项都将设置为 display: none
(隐藏类)。在上面的示例标记中,这意味着类别 #2 现在要显示的元素为零。我希望隐藏 .resources-files-container
的整个 div(直到他们选择另一个合适的过滤器)。
几个小时以来,我一直在尝试解决这个问题,并且进行了大量搜索(我找到了一些符合我的部分标准的解决方案,但不是这个特定案例)。除了这个特定部分,我已经弄清楚了整个应用程序。以下 jQuery 与我遇到的这个特定问题并不特别相关,只是为了给你一些背景信息:
// only run if we're in the portal
if ($("#portal-container").length) {
// get the unique list of classnames
var classes = {};
$('.attachment-list li').each(function() {
$($(this).attr('class').split(' ')).each(function() {
if (this !== '') {
classes[this] = this;
}
});
});
//build the list items
class_list = '';
for (class_name in classes) {
class_list += '<li class="'+class_name+'">'+class_name+'</li>';
};
// append the resulting list to the page
$(class_list).appendTo('#resource-filter ul');
// sorting functionality
$('#portal-page').on('click', '#resource-filter li', function() {
// set the current filter
var filterVal = $(this).attr('class');
// add current state to filter button
$('#resource-filter li.current').removeClass('current');
$(this).addClass('current');
// filtering function
if(filterVal == 'filter-all') {
$('.attachment-list li.hidden').fadeIn('slow').removeClass('hidden');
} else {
$('.attachment-list li').each(function() {
if(!$(this).hasClass(filterVal)) {
$(this).fadeOut('normal').addClass('hidden');
} else {
$(this).fadeIn('slow').removeClass('hidden');
}
});
}
});
}
我非常感谢任何建议。
最佳答案
$(".resources-files-container")
.filter(function(){
return $(this).find("li:visible").length == 0;
})
.hide();
将 .resources-files-container
元素列表过滤为那些没有可见 li
元素的列表,然后隐藏过滤后的集合。
关于javascript - 如果隐藏了 child ,如何隐藏 parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25732491/