如何隐藏未包含有效图片的DIV容器?
问题解决:隐藏包含空
<img>标签的DIV 问题原因
你的代码错误地尝试获取外层.image-box容器的src属性,但src是内部<img>标签的专属属性,容器本身不存在该属性,导致判断逻辑完全失效。
修正后的代码
jQuery 核心代码
$(function() { $('.image-box').each(function() { // 定位当前容器内的img元素,获取其src属性 const imgSrc = $(this).find('img').attr('src'); // 判断src是否为空或未定义 if (!imgSrc) { $(this).hide(); } }) })
完整可运行示例
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style> .image-box { border: 1px solid red; width: 180px; height: 130px } </style> <div class="image-box"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s"> </div> <div class="image-box"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgjelULwWqZnw17bVmdar736yVvV8J7ie5ntx9QFbW&s"> </div> <div class="image-box"> <img> </div>
关键说明
$(this).find('img')精准定位当前.image-box容器内的图片元素!imgSrc同时覆盖两种异常情况:<img>标签无src属性(返回undefined)、src属性值为空字符串('')- 执行后,包含空
<img>标签的红色边框容器会被自动隐藏
内容的提问来源于stack exchange,提问作者abcid d
相关产品推荐
相关产品推荐

