jquery / javascript - 如果包含图像被破坏,则隐藏div

时间:2010-12-14 16:06:00

标签: javascript jquery html

我有一个带有'userFeatureProductImage'类的div。这个div是重复的,但偶尔会有一个破碎的图像可能会通过,所以我想隐藏div作为预防措施,如果确实发生这种情况。我怎么能这样做?

4 个答案:

答案 0 :(得分:4)

只有在图像有效时才会触发加载事件:

$('.userFeatureProductImage').hide();
$('.userFeatureProductImage img').load(function() {
  $(this).closest('.userFeatureProductImage').show();
});

答案 1 :(得分:2)

使用图像发生错误时调用的error事件:

$(".userFeatureProductImage img").error(function(){
   $(this).parent().hide();
});

示例:http://jsfiddle.net/jonathon/vWwpc/

答案 2 :(得分:2)

您可以尝试这样的事情:

<script type="text/javascript" 
        src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
     function hideBrokenImage(id) {
          $(id.+"userFeatureProductImage").hide();
     }
</script>
<div id="imageFilename" class="userFeatureProductImage">
     <img src="imageFilename.gif" onerror="hideBrokenImage(imageFilename);" />
</div>

显然动态创建了imageFilename。

答案 3 :(得分:0)