我有一個包含一堆圖像的網頁。 有時,該圖像不可用,所以在客戶端的瀏覽器中會顯示損壞的圖像。 ajax
如何使用jQuery獲取圖像集,將其過濾爲損壞的圖像而後替換src? 瀏覽器
-我認爲使用jQuery會更容易,可是事實證實,僅使用純JavaScript解決方案(即Prestaul提供的解決方案)要容易得多。 async
若是像我這樣的人嘗試將error
事件附加到動態HTML img
標籤上,我想指出的是,有一個陷阱: ide
顯然,與大多數標準相反, img
錯誤事件在大多數瀏覽器中不會冒泡 。 this
所以,相似如下內容將不起做用 : url
$(document).on('error', 'img', function () { ... })
但願這對其餘人有幫助。 我但願我已經在此線程中看到了這一點。 可是,我沒有。 因此,我添加了它 spa
我使用內置的error
處理程序: .net
$("img").error(function () { $(this).unbind("error").attr("src", "broken.gif"); });
編輯:在jQuery 1.8及更高版本中不建議使用error()
方法。 相反,您應該使用.on("error")
代替: 線程
$("img").on("error", function () { $(this).attr("src", "broken.gif"); });
;(window.jQuery || window.Zepto).fn.fallback = function (fallback) { return this.one('error', function () { var self = this; this.src = (fallback || 'http://lorempixel.com/$width/$height') .replace(/\$(\w+)/g, function (m, t) { return self[t] || ''; }); }); };
您能夠經過$*
傳遞佔位符路徑並從失敗的圖像對象訪問全部屬性: rest
$('img').fallback('http://dummyimage.com/$widthx$height&text=$src');
http://jsfiddle.net/ARTsinn/Cu4Zn/
CoffeeScript變體:
我修復了Turbolinks的一個問題,即便該圖像確實存在,有時也會在Firefox中引起.error()方法。
$("img").error -> e = $(@).get 0 $(@).hide() if !$.browser.msie && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0)
我經過如下兩個簡單功能解決了個人問題:
function imgExists(imgPath) { var http = jQuery.ajax({ type:"HEAD", url: imgPath, async: false }); return http.status != 404; } function handleImageError() { var imgPath; $('img').each(function() { imgPath = $(this).attr('src'); if (!imgExists(imgPath)) { $(this).attr('src', 'images/noimage.jpg'); } }); }