我非常接近但却无法到达那里。
如果内部的跨距是空的,我想在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>
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'});
};
});
感谢。
编辑:目前它删除所有div,而不仅仅是具有空span标记的div。
答案 0 :(得分:5)
有两个主要问题:
$('span:empty')
在整个文档中搜索空跨度,并在结果上调用html()
来访问第一个匹配项的HTML。您希望通过$(this).find("span:empty")
$('.accordion-content div').css({'display' : 'none'});
隐藏所有匹配元素。
此外,无需致电html()
,您知道它是空的,并且jQuery具有内置功能,可以在元素display: none
上设置hide
。
如果要隐藏div,如果其中的任何范围为空,则:
$('.accordion-content div:has(span:empty)').hide();
如果你想隐藏div,如果所有跨越它是空的,那么:
$('.accordion-content div').filter(function(i, obj) {
return $(this).find('span:parent').length == 0;
}).hide();
如果div没有任何跨度,那也会隐藏div,所以为了完整性,这会隐藏那些有跨度的,但只有空的:
$('.accordion-content div:has(span)').filter(function(i, obj) {
return $(this).find('span:parent').length == 0;
}).hide();