使用jquery在img src为空时隐藏父元素

使用jquery在img src为空时隐藏父元素,jquery,hide,element,parent,Jquery,Hide,Element,Parent,生成的html: <div class="fp-thumbnail"> <img src="" /></div> Css不确定是否需要: .hide{display:none !important;} 更新:它确实在js小提琴中工作——但在网站上不工作 更具体地说:我想隐藏整个div,而不仅仅是图像 第二次更新:在实践中,没有一个解决方案比我已有的更好,所以我采用了不同的方法。对于那些至少尝试过的人,谢谢你的帮助 试试这样的方法: $("img[src='

生成的html:

<div class="fp-thumbnail"> <img src="" /></div>
Css不确定是否需要:

.hide{display:none !important;}
更新:它确实在js小提琴中工作——但在网站上不工作

更具体地说:我想隐藏整个div,而不仅仅是图像


第二次更新:在实践中,没有一个解决方案比我已有的更好,所以我采用了不同的方法。对于那些至少尝试过的人,谢谢你的帮助

试试这样的方法:

$("img[src='']").parent(".fp-thumbnail").addClass("hide");

你可以试试这种方法

var $img = $('img');       // Cache the images

$img.each(function(){      // Loop over multiple image tags
   var $this = $(this);    
  if( $this.attr('src') === ''){      // If src is empty
      $this.closest('div.fp-thumbnail').hide();  // Hide the corresponding parent
  }
});

如果只想对特定的图像执行此操作,可以删除.each循环并为图像指定特定的选择器。

@dystroy它看起来像是在js小提琴中,但在网站上却不是。@matt那么您需要提供更多信息,也许还需要执行基本调试。确实,您的代码正在运行。您是否可以在站点上检查是否存在可能会停止其余代码处理的Javascript错误。在你的网站上也检查jQuery的版本。为什么要投票?这个问题清楚地表明,除非是作为自我回答,否则没有足够的信息可以回答。注意,提问者的原始代码同样有效——一把小提琴就证明了这一点nothing@JanDvorak原始小提琴将选择图像上所有祖先的div,而不仅仅是它的父div。@Musa这个解释应该成为答案的一部分,或者一个自己的答案注意询问者的原始代码也可以工作
var $img = $('img');       // Cache the images

$img.each(function(){      // Loop over multiple image tags
   var $this = $(this);    
  if( $this.attr('src') === ''){      // If src is empty
      $this.closest('div.fp-thumbnail').hide();  // Hide the corresponding parent
  }
});