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

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


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


当前回答

我使用内置的错误处理程序:

$("img").error(function () {
    $(this).unbind("error").attr("src", "broken.gif");
});

编辑:error()方法在jquery 1.8及更高版本中已弃用。相反,你应该使用.on("error"):

$("img").on("error", function () {
    $(this).attr("src", "broken.gif");
});

其他回答

$(window).bind('load', function() {
  $('img').each(function() {
    if( (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) 
    ||  this.readyState == 'uninitialized'                                  ) {
        $(this).attr('src', 'missing.jpg');
    }
  });
});

来源:http://www.developria.com/2009/03/jquery-quickie--broken-images.html

这是JavaScript,应该是跨浏览器兼容的,并且没有丑陋的标记onerror="":

var sPathToDefaultImg = 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
    validateImage = function( domImg ) {
        oImg = new Image();
        oImg.onerror = function() {
            domImg.src = sPathToDefaultImg;
        };
        oImg.src = domImg.src;
    },
    aImg = document.getElementsByTagName( 'IMG' ),
    i = aImg.length;

while ( i-- ) {
    validateImage( aImg[i] );
}

CODEPEN:

使用JavaScript处理图像的onError事件以重新分配其源:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}
<img src="image.png" onerror="imgError(this);"/>

或者没有JavaScript函数:

<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />

下面的兼容性表列出了支持错误功能的浏览器:

http://www.quirksmode.org/dom/events/error.html

更好的呼叫使用

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

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

我创建了一个小提琴来取代破碎的图像使用"onerror"事件。 这可能对你有帮助。

    //the placeholder image url
    var defaultUrl = "url('https://sadasd/image02.png')";

    $('div').each(function(index, item) {
      var currentUrl = $(item).css("background-image").replace(/^url\(['"](.+)['"]\)/, '$1');
      $('<img>', {
        src: currentUrl
      }).on("error", function(e) {
        $this = $(this);
        $this.css({
          "background-image": defaultUrl
        })
        e.target.remove()
      }.bind(this))
    })