如果找不到源图像,如何显示备用图像?(onerror 在 IE 中工作,但不在 mozilla 中工作)

2022-08-30 02:58:52

如果找不到源图像,我需要在表格的单元格中显示备用图像。目前,下面的代码用于执行此操作。

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中不起作用。

请告诉我一些适用于所有浏览器的解决方案。


答案 1

我认为这很好,很短

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

但是,要小心。如果 onerror 图像本身生成错误,则用户的浏览器将陷入无限循环。


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

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

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


新增功能我想添加一个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 标记(如果它试图显示不良图像)。


答案 2

我得到了我的查询的解决方案:

我做了这样的事情:

cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>"

function setDefaultImage(source){
        var badImg = new Image();
        badImg.src = "video.png";
        var cpyImg = new Image();
        cpyImg.src = source.src;

        if(!cpyImg.width)
        {
            source.src = badImg.src;
        }

    }


    function onImgError(source){
        source.src = "video.png";
        source.onerror = ""; 
        return true; 
    } 

这样,它就可以在所有浏览器中工作。