0

我有一个加载一堆图像的页面。

一些链接指向不存在的图像,因此浏览器在尝试检索这些图像时会抛出 404。

这是问题的一个例子:

<div>01<img id="01" src="http://i.imgur.com/ydiBX0Bb.jpg" /></div><hr />
<div>02<img id="02" src="http://i.imgur.com/aObMmrWb.jpg" /></div><hr />
<div>03<img id="03" src="http://www.google.com/does_not_exist.jpg" /></div><hr />
<div>04<img id="04" src="http://www.google.com/also_does_not_exist.jpg" /></div><hr />
<div>05<img id="05" src="http://i.imgur.com/kJezbugb.jpg" /></div><hr />

还有小提琴:

http://jsfiddle.net/amv3z/

图像 1、2 和 5 都可以正常加载。图像 3 和 4 不存在。

因此,我的开发控制台会吐出以下错误:

GET http://www.google.com/does_not_exist.jpg 404 (Not Found)
GET http://www.google.com/also_does_not_exist.jpg 404 (Not Found)

我可以使用 JavaScript / jQuery 获取引发 404 错误的图像链接列表吗?

谢谢!

4

1 回答 1

0

您所寻求的似乎已经在 stackoverflow 上。

单击此处查看原始问题。

您需要做的基本上是将任一代码片段放入 for 循环中。如果你想这样做,你将需要一组图像源。

链接中的普通 JS 函数:

function resourceExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

使用链接中提到的功能的示例:

var aImageSrc = ['path/to/img/1', 'path/to/non/existant/img/2', 'path/to/other/img'];
var aErrorSrc = []; //Will be filled with non-existant images.
var imgStr = '';

for (var i = 0; i < (aImageSrc.length-1); i++) {
    if (!resourceExists(aImageSrc[i])) {
        aErrorSrc.push(aImageSrc[i]);
    } else {
        //Append image to string if it exists.
        imgStr += '<image src="'+aImageSrc[i]+'" alt="Don't forget the people with lesser visibility" />';
    }
}

//Append the string to any element you need to create
//If you want to append the image anyways even tho it does not exist,
//You could remove the else in the for-loop and just put the append line below it.

//To top it off, do a console log to display all the errors.
console.log(aErrorSrc);

笔记

不要忘记console.log();从您的脚本中删除 's,因为 IE(ofc,还有什么......)有点愚蠢,当控制台关闭时,当它遇到 console.log 时,它将停止执行任何操作,或者根本不执行任何操作。

希望这有帮助

- 席德

于 2013-10-16T21:31:33.187 回答