我是如此接近,但只是不能到达那里.
我想在div中添加一个类display:none,如果它内部的跨度是空的.
HTML:
<div class="accordion-content default">
<div><span><?php the_field(''); ?></span><span><?php the_field('tenure1'); ?></span></div>
<div><span><?php the_field(''); ?></span><span><?php the_field('tenure2'); ?></span></div>
<div><span><?php the_field(''); ?></span><span><?php the_field('tenure3'); ?></span></div>
<div><span><?php the_field(''); ?></span><span><?php the_field('tenure4'); ?></span></div>
<div><span><?php the_field(''); ?></span><span><?php the_field('tenure5'); ?></span></div>
<div><span><?php the_field(''); ?></span><span><?php the_field('tenure6'); ?></span></div>
<div><span><?php the_field(''); ?></span><span><?php the_field('tenure7'); ?></span></div>
<div><span><?php the_field(''); ?></span><span><?php the_field('tenure8'); ?></span></div>
<div><span><?php the_field(''); ?></span><span><?php the_field('tenure9'); ?></span></div>
<div><span><?php the_field(''); ?></span><span><?php the_field('tenure10'); ?></span></div>
<div><span>Yearsl</span><span><?php the_field(''); ?></span></div>
</div>
Run Code Online (Sandbox Code Playgroud)
JQUERY
//hide unused fields
//iterate over each div
$('.accordion-content div').each(function(i, obj) {
// if the spans it contain are empty
if ($('span:empty').html().length == 0 ) {
//do not display the parent div
$('.accordion-content div').css({'display' : 'none'});
};
});
Run Code Online (Sandbox Code Playgroud)
谢谢.
编辑:目前它删除所有div不只是具有空span标签的div.
有两个主要问题:
$('span:empty')在整个文档中搜索空跨度,并调用html()结果访问第一个匹配的HTML.你想在 div中查看$(this).find("span:empty").
$('.accordion-content div').css({'display' : 'none'});隐藏所有匹配元素.
此外,不需要调用html(),你知道它是空的,jQuery有一个内置函数来设置display: none元素:hide.
如果要隐藏div,如果其中的任何跨度为空,则:
$('.accordion-content div:has(span:empty)').hide();
Run Code Online (Sandbox Code Playgroud)
如果你想隐藏div,如果里面的所有跨距都是空的,那么:
$('.accordion-content div').filter(function(i, obj) {
return $(this).find('span:parent').length == 0;
}).hide();
Run Code Online (Sandbox Code Playgroud)
如果它根本没有任何跨度,那也会隐藏div,所以为了完整性,这隐藏了具有跨度的那些,但只有空的:
$('.accordion-content div:has(span)').filter(function(i, obj) {
return $(this).find('span:parent').length == 0;
}).hide();
Run Code Online (Sandbox Code Playgroud)