我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。

我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?


—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。


当前回答

我用这两个简单的函数解决了这个问题:

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');
        }
    });
}

其他回答

如果图像无法加载(例如,因为它不在提供的URL中),图像URL将被更改为默认值,

有关.error()的更多信息

美元(img)。On('错误',函数(e) { (美元)。attr(“src”、“broken.png”); });

我使用惰性加载,必须这样做,以使它正常工作:

lazyload();

var errorURL = "https://example.com/thisimageexist.png";

$(document).ready(function () {
  $('[data-src]').on("error", function () {
    $(this).attr('src', errorURL);
  });
});

这是一个蹩脚的技巧,但它几乎是可以保证的:

<img onerror="this.parentNode.removeChild(this);">
(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] || ''; }
    );
  });
};
    

你可以传递一个占位符路径,并通过$*访问失败图像对象的所有属性:

$('img').fallback('http://dummyimage.com/$widthx$height&text=$src');

http://jsfiddle.net/ARTsinn/Cu4Zn/

更好的呼叫使用

jQuery(window).load(function(){
    $.imgReload();
});

因为使用文档。ready并不一定意味着图像被加载,只是HTML。因此,不需要延迟调用。