[英]Hide a list item if the next siblings are all hidden
I have the following list: 我有以下清单:
<ul>
<li class="title">A</li>
<li class="item" style="display: none">a1</li>
<li class="item" style="display: none">a2</li>
<li class="title">B</li>
<li class="item" style="display: none">b1</li>
<li class="item">b2</li>
</ul>
I would like to create a JavaScript function which checks if the two list items after A are both set to display: none. 我想创建一个JavaScript函数,该函数检查A之后的两个列表项是否都设置为显示:无。 If they're both set to display: none, then set their title "A" to display: none as well.
如果它们都设置为显示:无,则将其标题“ A”设置为显示:无。
I want the script to do the checking for B as well, but don't hide "B" because not all the siblings after it are set to display: none. 我希望脚本也对B进行检查,但不要隐藏“ B”,因为不是所有在其后的兄弟都设置为显示:无。
I'm thinkering how to proceed for a few hours now but have no idea. 我正在考虑如何继续几个小时,但不知道。 Can you give me some ideas how can I do that, not necessarily code, just ideas.
您能给我一些想法吗,我不一定要编码,而只是想法。 Thanks!
谢谢!
You can loop through all li.title
and walk down all the next siblings of each li.title
instance that are .item
using Element.matches()
and store in array. 你可以通过所有循环
li.title
和走各的所有兄弟姐妹旁边li.title
被实例.item
使用Element.matches()
和存储阵列。
Then check that array of item siblings for all hidden or not and use that determination what to do with display for current instance of li.title
然后检查所有是否隐藏的同级项数组,并使用该决定处理
li.title
当前实例的li.title
const titles = document.querySelectorAll('li.title'); Array.from(titles).forEach(li => { const items = []; let next = li.nextElementSibling; while (next && next.matches('.item')) { items.push(next); next = next.nextElementSibling; } const hide = items.every(n => n.style.display === 'none') if (hide) { li.style.display = 'none'; } else { li.style.removeProperty('display') } })
<ul> <li class="title">A</li><!-- should get hidden--> <li class="item" style="display: none">a1</li> <li class="item" style="display: none">a2</li> <li class="title" style="display: none">B</li><!-- should get shown --> <li class="item" style="display: none">b1</li> <li class="item">b2</li> </ul>
The answer by @charlietfl is a pretty good one. @charlietfl的答案是一个很好的答案。 But in case you have no problem with using jQuery, I find the below code a bit simpler.
但是,如果您使用jQuery没问题,我发现以下代码会更简单。
You can learn more about nextAll() here . 您可以在此处了解有关nextAll()的更多信息。
const titles = $('.title');
titles.each(function() {
const siblings = $(this).nextAll().slice(0, 2);
const siblingsWithDisplayNone = siblings.filter(function() {
return $(this).css('display') == 'none'
});
if (siblings.length === siblingsWithDisplayNone.length) {
$(this).css('display', 'none')
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.