如果找不到源图像,我需要在表格的单元格中显示备用图像。
目前,下面的代码用于执行此操作。
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 中无效。
请告诉我一些适用于所有浏览器的解决方案。
我觉得这很好,也很短
<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';" />
通过调用 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 标签中,如果它试图显示不良图像。