javascript 如果头部 404 不是隐藏它,则 jQuery 检查图像是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12994419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery to check image exists if head 404 than hide it
提问by user1761824
Using php to get 100 photos url from a db and show them on a page, but some photos may no longer exist. If the photo url is fail (404) I want to use jquery to hide the image and don't want to show any error picture. This is my code but it doesn't work.
使用 php 从数据库中获取 100 张照片 url 并将它们显示在页面上,但有些照片可能不再存在。如果照片 url 失败 (404) 我想使用 jquery 隐藏图像并且不想显示任何错误图片。这是我的代码,但它不起作用。
html
html
<div id=test>
<img src="http://test.com/test1.jpg" />
<img src=" http://test.com/test2.jpg" />
<img src="http://test.com/test3.jpg" />
</div>
jquery
查询
var pic_list = jQuery("#test img");
pic_list.load(function () {
var http = new XMLHttpRequest();
http.open('HEAD', pic_list, false);
http.send();
if (http.status == 404) {
pic_list.hide();
} else {
pic_list.show();
}
});
回答by Fabrício Matté
Sending multiples ajax requests is unnecessary when you can use the onerror
event.
可以使用onerror
事件时,不需要发送多个ajax请求。
Check out the related jQuery/Javascript to replace broken imagespost.
查看相关的jQuery/Javascript 以替换损坏的图像帖子。
Adapting that to your needs:
使其适应您的需求:
HTML:
HTML:
<img src="someimage.png" onerror="imgError(this);" />
JS:
JS:
function imgError(image){
image.style.display = 'none';
}
Or with jQuery:
或者使用 jQuery:
function imgError(image){
$(image).hide();
}
I normally wouldn't use inline JS in the HTML, and even considered using an .error
handler:
我通常不会在 HTML 中使用内联 JS,甚至考虑使用.error
处理程序:
$('#test img').error(function() {
$(this).hide();
});
Butthe above will not work if the handler attaching is executed after the error event has fired, hence I suggest the first solution.
但是如果在错误事件触发后执行处理程序附加,则上述方法将不起作用,因此我建议第一个解决方案。
回答by sachleen
The second parameter of the open
method is a url, not an array of HTML elements.
该open
方法的第二个参数是一个 url,而不是一个 HTML 元素数组。
So you can use each
to iterate over the elements, get their src
attribute using .attr()
and pass that into the method.
因此,您可以使用each
迭代元素,src
使用它们获取属性.attr()
并将其传递给方法。
Since you have the images loaded already, instead of doing another request for each one, you might be able to use a method I discussed in another question: Check if user is blocking 3rd party domain
由于您已经加载了图像,而不是对每个图像进行另一个请求,您可以使用我在另一个问题中讨论的方法:检查用户是否阻止了 3rd 方域
If your images aren't of fixed height/width, a non-existent image will produce a small icon indicating the image doesn't exist. You can use the size of the image to see if the image was loaded or not.
如果您的图像不是固定的高度/宽度,不存在的图像将产生一个小图标,表明该图像不存在。您可以使用图像的大小来查看图像是否已加载。