如果没有使用Javascript设置默认图像,请检查图像是否存在

时间:2022-11-23 09:26:37

I have a lot of images. like:

我有很多图像。喜欢:

<img src="src1"/>
<img src="src2"/>
<img src="src3"/>

Some of the image maybe do not exist. So the browser will show a broken image picture. It is ugly. How to use Javascript not jQuery to determine whether an image exists? If not, give a local image to replace it. Thank you.

有些图像可能不存在。因此浏览器将显示损坏的图像图片。这很难看。如何使用Javascript而不是jQuery来确定图像是否存在?如果没有,请提供本地图像以替换它。谢谢。

I tried the code , it replaced all the images not only those not exist.

我尝试了代码,它取代了所有不仅存在的图像。

function imgError(image) {
            image.onerror = "";
            image.src = "http://www.hi-pda.com/forum/uc_server/data/avatar/000/85/69/99_avatar_middle.jpg?random=10.20420048222877085";
            return true;
        }

        var imgs = document.getElementsByTagName("img");
        for (var i = 0; i < imgs.length; i++) {
            imgs[i].onerror=imgError(imgs[i]);
        }

the images are

图像是

<img src="rrrrr"  />
    <img src="http://www.hi-pda.com/forum/uc_server/data/avatar/000/52/56/39_avatar_middle.jpg"/>

the first picture does not exist , the second one exists. when I run it in chrome , all the picture were replaced...

第一张图片不存在,第二张图片存在。当我在chrome中运行时,所有图片都被替换了......

3 个解决方案

#1


6  

Simple solution:

<img src="http://src1/img.jpg" onerror="this.src='http://src1/error-img.jpg';">

Set within the img tag

在img标签内设置

Update

A better solution which stops infinite loops - thanks @stom

一个更好的解决方案,可以阻止无限循环 - 感谢@stom

<img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';">

Originally posted by @svend here

最初由@svend在这里发布

#2


1  

I solved it using this code:

我用这段代码解决了它:

function nofind() {
    var img = event.srcElement
    img.src="http://www.cnblogs.com/sys/common/image/fileoperation/icon/default.gif";
    img.onerror = null; 
}

var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
    imgs[i].onError=nofind;
}

#3


0  

You can bind onerror event listener to all the images in the DOM..

您可以将onerror事件侦听器绑定到DOM中的所有图像。

#1


6  

Simple solution:

<img src="http://src1/img.jpg" onerror="this.src='http://src1/error-img.jpg';">

Set within the img tag

在img标签内设置

Update

A better solution which stops infinite loops - thanks @stom

一个更好的解决方案,可以阻止无限循环 - 感谢@stom

<img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';">

Originally posted by @svend here

最初由@svend在这里发布

#2


1  

I solved it using this code:

我用这段代码解决了它:

function nofind() {
    var img = event.srcElement
    img.src="http://www.cnblogs.com/sys/common/image/fileoperation/icon/default.gif";
    img.onerror = null; 
}

var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
    imgs[i].onError=nofind;
}

#3


0  

You can bind onerror event listener to all the images in the DOM..

您可以将onerror事件侦听器绑定到DOM中的所有图像。