jQuery / JavaScript替换损坏的图像

我有一个包含一堆图像的网页。 有时,该图像不可用,所以在客户端的浏览器中会显示损坏的图像。 ajax

如何使用jQuery获取图像集,将其过滤为损坏的图像而后替换src? 浏览器


-我认为使用jQuery会更容易,可是事实证实,仅使用纯JavaScript解决方案(即Prestaul提供的解决方案)要容易得多。 async


#1楼

若是像我这样的人尝试将error事件附加到动态HTML img标签上,我想指出的是,有一个陷阱: ide

显然,与大多数标准相反, img错误事件在大多数浏览器中不会冒泡this

所以,相似如下内容将不起做用url

$(document).on('error', 'img', function () { ... })

但愿这对其余人有帮助。 我但愿我已经在此线程中看到了这一点。 可是,我没有。 因此,我添加了它 spa


#2楼

我使用内置的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");
});

#3楼

;(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/


#4楼

CoffeeScript变体:

我修复了Turbolinks的一个问题,即便该图像确实存在,有时也会在Firefox中引起.error()方法。

$("img").error ->
  e = $(@).get 0
  $(@).hide() if !$.browser.msie && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0)

#5楼

我经过如下两个简单功能解决了个人问题:

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');
        }
    });
}
相关文章
相关标签/搜索