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

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


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


当前回答

这是一个快速和肮脏的方法来替换所有破碎的图像,没有必要改变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"),
            });
        }
  });

其他回答

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

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

如果你已经用innerHTML插入了img,比如:$("div")。innerHTML = <img src="wrong-uri">,你可以加载另一个图像,如果它失败了,例如:

<script>
    function imgError(img) {
        img.error="";
        img.src="valid-uri";
    }
</script>

<img src="wrong-uri" onerror="javascript:imgError(this)">

为什么javascript: _needed?因为通过innerHTML中的脚本标记注入DOM的脚本在注入时不会运行,所以必须显式。

当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函数。

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

$("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");
});

我找不到适合我需要的脚本,所以我做了一个递归函数来检查损坏的图像,并尝试每四秒重新加载它们,直到它们修复。

我将它限制为10次尝试,因为如果它没有加载,那么图像可能不会出现在服务器上,函数将进入一个无限循环。不过我仍在测试中。请随意调整它:)

var retries = 0;
$.imgReload = function() {
    var loaded = 1;

    $("img").each(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {

            var src = $(this).attr("src");
            var date = new Date();
            $(this).attr("src", src + "?v=" + date.getTime()); //slightly change url to prevent loading from cache
            loaded =0;
        }
    });

    retries +=1;
    if (retries < 10) { // If after 10 retries error images are not fixed maybe because they
                        // are not present on server, the recursion will break the loop
        if (loaded == 0) {
            setTimeout('$.imgReload()',4000); // I think 4 seconds is enough to load a small image (<50k) from a slow server
        }
        // All images have been loaded
        else {
            // alert("images loaded");
        }
    }
    // If error images cannot be loaded  after 10 retries
    else {
        // alert("recursion exceeded");
    }
}

jQuery(document).ready(function() {
    setTimeout('$.imgReload()',5000);
});