3 回答

TA貢獻1803條經驗 獲得超6個贊
我覺得這很好,很簡短
<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標簽中,以使其嘗試顯示不良圖片。

TA貢獻1895條經驗 獲得超3個贊
我已經為我的查詢找到了解決方案:
我做了這樣的事情:
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;
}
這樣,它可以在所有瀏覽器中工作。

TA貢獻1840條經驗 獲得超5個贊
如果您愿意使用PHP解決方案:
<td><img src='<?PHP
$path1 = "path/to/your/image.jpg";
$path2 = "alternate/path/to/another/image.jpg";
echo file_exists($path1) ? $path1 : $path2;
?>' alt='' />
</td>
////編輯OK,這是JS版本:
<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>
<script type='text/javascript'>
document.getElementById('myImage').src = "newImage.png";
document.getElementById('myImage').onload = function() {
alert("done");
}
document.getElementById('myImage').onerror = function() {
alert("Inserting alternate");
document.getElementById('myImage').src = "alternate.png";
}
</script>
添加回答
舉報