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

问题描述

如果找不到源图像,我需要在表格的单元格中显示替代图像.目前使用下面的代码来做到这一点.

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; 
}

现在的问题是上述解决方案在 Internet Explorer 中有效,但在 mozilla 中无效.

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.

推荐答案

我觉得这个很好很简短

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

但是,要小心.如果 onerror 图片本身产生错误,用户的浏览器就会陷入死循环.

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

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

EDITTo 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';" />

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

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

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

NEWI 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' />

您只需将 class='backup_picture' 添加到您希望备份图片在尝试显示不良图像时加载的任何 img 标签.

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 中无效)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:19