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

我如何使用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');
        }
    });
}

其他回答

我也有同样的问题。这个代码在我的案子上很有效。

// Replace broken images by a default img
$('img').each(function(){
    if($(this).attr('src') === ''){
      this.src = '/default_feature_image.png';
    }
});

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

当OP正在寻找替换SRC时,我相信许多人遇到这个问题可能只希望隐藏损坏的图像,在这种情况下,这个简单的解决方案对我来说非常有用。

使用内联JavaScript:

<img src="img.jpg" onerror="this.style.display='none';"/>

使用外部JavaScript:

var images = document.querySelectorAll('img'); For (var I = 0;I < images.length;我+ +){ 图像[我]。Onerror = function() { this.style.display = '没有'; } } <img src='img.jpg' />

使用现代外部JavaScript:

document.querySelectorAll('img').forEach((img) => { img。Onerror = function() { This.style.display = 'none'; } }); <img src='img.jpg' />

参见浏览器对NodeList的支持。forEach和arrow函数。

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

有关.error()的更多信息

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

这是一个快速和肮脏的方法来替换所有破碎的图像,没有必要改变HTML代码;)

codepen例子

    $("img").each(function(){
        var img = $(this);
        var image = new Image();
        image.src = $(img).attr("src");
        var no_image = "https://dummyimage.com/100x100/7080b5/000000&text=No+image";
        if (image.naturalWidth == 0 || image.readyState == 'uninitialized'){
            $(img).unbind("error").attr("src", no_image).css({
                height: $(img).css("height"),
                width: $(img).css("width"),
            });
        }
  });