I'm trying to hide a parent div (i.e., #post) if the child div (i.e., .post-title) doesn't contain an <a>
tag. Any insight in how to accomplish this correctly with the code I've modified?
<div id="latest">
<div id="post">
<div class="post-image post-image-1"></div>
<div id="post-content">
<div class="post-title post-title-1"></div>
<div id="post-date"></div>
</div>
</div>
<div id="post">
<div class="post-image post-image-2"></div>
<div id="post-content">
<div class="post-title post-title-2"></div>
<div id="post-date"></div>
</div>
</div>
</div>
$('.post-title').not($('a').hide($("#post"));
答案 0 :(得分:5)
注意:复制
id
是犯罪行为。
通过将所有id
对等方式更改为class
来实现正确,这应该有效:
$(function () {
$(".post-title").filter(function () {
return $(this).find("a").length == 0;
}).hide();
});
&#13;
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<div id="latest">
<div class="post">
<div class="post-image post-image-1"></div>
<div class="post-content">
<div class="post-title post-title-1">Hide This</div>
<div class="post-date"></div>
</div>
</div>
<div class="post">
<div class="post-image post-image-2"></div>
<div class="post-content">
<div class="post-title post-title-2"><a href="">Don't Hide</a></div>
<div class="post-date"></div>
</div>
</div>
</div>
&#13;
答案 1 :(得分:1)
首先:多次使用ID。每个ID都应该是唯一的:)
其次:$('.post').not( ':has(".post-title a")' ).addClass('hide')
答案 2 :(得分:1)
您可以简单地使用jQuery&#39; .filter
像这样:
{
"@rid": "#1:0",
"property": "ValueForA",
"connected": "[#2:0, #2:1]"
}
$('.post-title').filter(function(i) { return !$(this).find('a').length }).hide();
&#13;
$('.post-title').filter(function(i) { return !$(this).find('a').length }).hide();
&#13;
答案 3 :(得分:0)
只需使用jQuery的toggle使用布尔值来检查子项的长度:
/* Loop Through Parents */
$('#post').each(function() {
$(this).toggle($(this).children('a').length > 0);
});