2014-02-28 49 views
3

下面给出 http://www.bikewalls.com/pictures/abc.jpg图像URL(未加载)javascript/jquery检查图像是否存在?

我需要一个JavaScript/jQuery函数/代码以警告说上述网址有效或not.These网址将作为参数传递。以上例为例,将会非常有帮助。

+1

你在哪里写这个函数卡住了? –

+1

在[此前StackOverflow答案](http://stackoverflow.com/questions/9714525/javascript-image-url-verify/9714891#9714891)是一个函数称为'testImage()',它需要一个图像的URL来测试和会调用您的回调函数,并告诉您图像是否成功加载。 – jfriend00

回答

2

您可以使用onloadonerror回调是这样的:

var img = new Image(); 
var url = "http://www.vbarter.com/images/content/3/2/32799.JPG"; 
img.onload = function(){ 
    alert("the image exists"); 
    // display image or whatever you need 
}; 
img.onerror = function(){ 
    alert("error while loading.."); 
    // handle the error 
} 

img.src = url; 

FIDDLEhttp://jsfiddle.net/473GV/

0

快速和使用简单的jQuery:

$("<img/>") 
    .load(function() { 
     console.log("image loaded correctly"); 
    }) 
    .error(function() { 
     alert("error loading image"); 
    }) 
    .attr("src", $(originalImage).attr("src")); 

很明显,你必须适应这种变化这对你的具体情况,但你明白了。你可以阅读更多关于jQuery的$.error()here