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

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


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


当前回答

我创建了一个小提琴来取代破碎的图像使用"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))
    })

其他回答

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

<img onerror="this.parentNode.removeChild(this);">

如果有人像我一样,试图将错误事件附加到动态HTML img标记,我想指出的是,有一个陷阱:

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

所以,像下面这样的代码是行不通的:

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

希望这对其他人有所帮助。我希望我能在这个帖子里看到这个。但是,我没有。我把它加起来

这是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:

$(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

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

有关.error()的更多信息

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