img圖片載入失敗用預設圖片代替
阿新 • • 發佈:2019-01-04
onerror 事件在載入外部檔案(文件或影象)發生錯誤時觸發。
<img alt="{dr[title]}" src="{dr[img_url]}" onerror="this.src='/admin/skin/default/loadimg.gif'">
img 使用 onerror 以後,如果 onerror 指定的圖片也是不存在的話,會出現無限死迴圈 404。
<img src="image.gif" onerror="javascript:this.src='src/images/default.jpg';this.onerror = null">
jquery.error函式
jquery提供對應的事件處理函式
$('img').error(function(){
$(this).attr('src',"default.gif");
})
jquery.one函式
使用上面兩種方法,假如預設圖片也載入失敗,則變成死迴圈. 此時可使用one()繫結事件
$("img").one("error", function(e){
$(this).attr("src", "default.gif");
});
另外error事件,不支援冒泡,jquery.delegate函式捕捉不到error事件。