Javascript 查看img的src是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9022427/
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
see if src of img exists
提问by Tono Nam
when I place an img tag I create the src attribute dynamically. Is there a way of testing if the src (path where the image is located) actually exists with javascript in order to avoid getting:
当我放置一个 img 标签时,我会动态创建 src 属性。有没有一种方法可以测试 src(图像所在的路径)是否确实存在于 javascript 中,以避免出现:
回答by Sarfraz
You can use the error
event:
您可以使用该error
事件:
var im = document.getElementById('imageID'); // or select based on classes
im.onerror = function(){
// image not found or change src like this as default image:
im.src = 'new path';
};
Inline Version:
内联版本:
<img src="whatever" onError="this.src = 'new default path'" />
Or
或者
<img src="whatever" onError="doSomething();" />
<img>
tag supports these events:
<img>
标签支持这些事件:
abort
(onAbort)error
(onError)load
(onLoad)
abort
(中止时)error
(onError)load
(负载)
More Information:
更多信息:
回答by Fabrizio Calderan
you can make a previous ajax call (with head
method) and see the server return code
or you can use onerror
event to change url or make it hidden, e.g.
您可以进行先前的ajax调用(使用head
方法)并查看服务器返回代码,或者您可以使用onerror
事件来更改url或将其隐藏,例如
<img src="notexist.jpg" onerror="this.style.visibility = 'hidden'">
(I've used inline attribute just to explain the idea)
(我使用内联属性只是为了解释这个想法)
回答by Alexandre Strapacao G. Vianna
If you create the src dynamically with javascript you can use this:
如果您使用 javascript 动态创建 src,则可以使用:
var obj = new Image();
obj.src = "http://www.javatpoint.com/images/javascript/javascript_logo.png";
if (obj.complete) {
alert('worked');
} else {
alert('doesnt work');
}
回答by Madara's Ghost
You're approaching this the wrong way.
When you generate your links with the server side script, check it there whether the file exists or not (by using file_exists()
in PHP for example).
你以错误的方式接近这个。
当您使用服务器端脚本生成链接时,请检查该文件是否存在(file_exists()
例如在 PHP 中使用)。
You shouldn't rely on JavaScript when you can do it in the server side, as JavaScript can be altered and disabled.
当您可以在服务器端执行此操作时,您不应该依赖 JavaScript,因为可以更改和禁用 JavaScript。
Ask yourself how are you generating the src=
attributes, and check there whether the file exists or not, and provide an alternative.
问问自己如何生成src=
属性,并检查该文件是否存在,并提供替代方法。