2012-02-22 69 views
11

我想使用jquery检查给定URL上是否存在图像。例如,如何检查图像是否存在于此网址上。如何检查该网址是使用Jquery的有效图像源?

https://www.google.com/logos/2012/hertz-2011-hp.gif 

但不是在这个网址

http://www.google.com 
+0

参见[有](http://stackoverflow.com/questions/169625/regex-to-check-if-valid-url-在-jpg-png-gif中),[there](http://stackoverflow.com/questions/3381663/check-if-image-exists-with-given-url-using-jquery)和[有](http://stackoverflow.com/questions/4669111/is-this-a-valid-test-to-check-if-a-url-refers-to-an-image-in-js-jquery)这将是有用的 – komelgman 2012-02-22 12:46:27

+0

[Here](http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascrip点)是你可能要找的。 – buster 2012-02-22 12:46:46

回答

26
function IsValidImageUrl(url) { 
$("<img>", { 
    src: url, 
    error: function() { alert(url + ': ' + false); }, 
    load: function() { alert(url + ': ' + true); } 
}); 
} 

IsValidImageUrl("https://www.google.com/logos/2012/hertz-2011-hp.gif"); 
IsValidImageUrl("http://google.com"); 
+0

你测试过了吗?由于某种原因,我试图在Chrome中使用此代码,并且每件事情都会返回false – IcedDante 2014-08-07 14:06:56

+1

哦,这个负载发生在一个单独的线程中。我试图从错误加载方法返回true false,这是行不通的。 – IcedDante 2014-08-07 14:14:52