我的网站上有以下几行代码:
<div class="the-post-thumbnail">
<img src="" alt="" width="" height="" />
</div>
<div class="post-body">
<p><img src="" alt="" width="" height="" /></p>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p><img src="" alt="" width="" height="" /></p>
</div>
如何在 <p>
div中选择包含图片的第一个 post-body
标记,并根据是否有图像隐藏它在 the-post-thumbnail
的div中,否则,显示它?
答案 0 :(得分:1)
:has()
,您可以选择包含p
代码的img
代码:first
向其中的第一个p
代码hide()
和 show()
来切换可见性代码:
var ele = $('.post-body p:has(img):first');
if ($('.the-post-thumbnail img').length > 0)
ele.hide();
else
ele.show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="the-post-thumbnail">
<img src="" alt="#" width="" height="" />
</div>
<div class="post-body">
<p>
<img src="" alt="#" width="" height="" />
</p>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>
<img src="" alt="" width="" height="" />
</p>
</div>
答案 1 :(得分:0)
// $el will be the first p
$el = $("div.post-body").find("img").eq(0).closest("p");
if($(".the-post-thumbnail img").length==0)
$el.hide();
else
$el.show()