如果源图像未找到,如何显示替代图像? (onerror在IE中工作,但不在Mozilla中) [英] how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

查看:175
本文介绍了如果源图像未找到,如何显示替代图像? (onerror在IE中工作,但不在Mozilla中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果没有找到源图像,我需要在表格的单元格中显示替代图像。
目前下面的代码用于这样做。

  cell.innerHTML =< img height = 40 width = 40 src ='<%= request.getContextPath()%> /writeImage.htm'onError ='ImgErrorVideo(this);'> 
函数ImgErrorVideo(source){
source.src =video.png;
source.onerror =;
返回true;
}

现在问题在于上述解决方案是在Internet Explorer中工作,但不是



感谢
Jyoti

解决方案

我认为这是非常好的和简短的

 < img src =imagenotfound.gifalt =找不到图片onerror =this.src ='imagefound.gif'; /> 

但是,要小心。






编辑
为避免无限循环,立即从它中删除 onerror

 < img src =imagenotfound.gifalt =图片未找到onerror =this.onerror = null; this.src ='imagefound.gif'; /> 

通过调用 this.onerror = null 它将删除onerror,然后尝试获取备用图片。







我想添加一个jQuery的方式,如果这可以帮助任何人。

 < script> 
$(document).ready(function()
{
$(。backup_picture)on(error,function(){
$(this)。 attr('src','./images/nopicture.png');
});
});
< / script>

< img class ='backup_picture'src ='。/ images / nonexistent_image_file.png'/>

您只需将class ='backup_picture'添加到您想要备份图片的任何img标签即可如果它试图显示一个不好的图像加载。


I need to show an alternate image in cell of table if source image is not found. Currently below code is used to do so.

cell.innerHTML="<img height=40 width=40 src='<%=request.getContextPath()%>/writeImage.htm' onError='ImgErrorVideo(this);'>" 
function ImgErrorVideo(source){
        source.src = "video.png";
        source.onerror = ""; 
        return true; 
}

Now the problem is that the above is solution is working in Internet Explorer but not in mozilla.

Please tell me some solution which works in all browsers.

Thanks Jyoti

解决方案

I think this is very nice and short

<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />

But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.


EDIT To avoid endless loop, remove the onerror from it at once.

<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />

By calling this.onerror=null it will remove the onerror then try to get the alternate image.


NEW I would like to add a jQuery way, if this can help anyone.

<script>
$(document).ready(function()
{
    $(".backup_picture").on("error", function(){
        $(this).attr('src', './images/nopicture.png');
    });
});
</script>

<img class='backup_picture' src='./images/nonexistent_image_file.png' />

You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.

这篇关于如果源图像未找到,如何显示替代图像? (onerror在IE中工作,但不在Mozilla中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆