猿问

如何显示备用图像,如果找不到源图像?(在的onerror IE而不是在Mozilla工作)

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


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


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


撒科打诨
浏览 659回答 3
3回答

慕码人8056858

我觉得这很好,很简短<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(){&nbsp; &nbsp; $(".backup_picture").on("error", function(){&nbsp; &nbsp; &nbsp; &nbsp; $(this).attr('src', './images/nopicture.png');&nbsp; &nbsp; });});</script><img class='backup_picture' src='./images/nonexistent_image_file.png' />您只需要将class ='backup_picture'添加到要加载备用图片的任何img标签中,以使其尝试显示不良图片。

蛊毒传说

我已经为我的查询找到了解决方案:我做了这样的事情:cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>"function setDefaultImage(source){&nbsp; &nbsp; &nbsp; &nbsp; var badImg = new Image();&nbsp; &nbsp; &nbsp; &nbsp; badImg.src = "video.png";&nbsp; &nbsp; &nbsp; &nbsp; var cpyImg = new Image();&nbsp; &nbsp; &nbsp; &nbsp; cpyImg.src = source.src;&nbsp; &nbsp; &nbsp; &nbsp; if(!cpyImg.width)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; source.src = badImg.src;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; function onImgError(source){&nbsp; &nbsp; &nbsp; &nbsp; source.src = "video.png";&nbsp; &nbsp; &nbsp; &nbsp; source.onerror = "";&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp;&nbsp; &nbsp; }&nbsp;这样,它可以在所有浏览器中工作。

慕斯709654

如果您愿意使用PHP解决方案:<td><img src='<?PHP&nbsp; $path1 = "path/to/your/image.jpg";&nbsp; $path2 = "alternate/path/to/another/image.jpg";&nbsp; echo file_exists($path1) ? $path1 : $path2;&nbsp;&nbsp; ?>' alt='' /></td>////编辑OK,这是JS版本:<table><tr><td><img src='' id='myImage' /></td></tr></table><script type='text/javascript'>&nbsp; document.getElementById('myImage').src = "newImage.png";&nbsp; document.getElementById('myImage').onload = function() {&nbsp;&nbsp; &nbsp; alert("done");&nbsp;&nbsp; }&nbsp; document.getElementById('myImage').onerror = function() {&nbsp;&nbsp; &nbsp; alert("Inserting alternate");&nbsp; &nbsp; document.getElementById('myImage').src = "alternate.png";&nbsp;&nbsp; }</script>
随时随地看视频慕课网APP
我要回答