下面给出 http://www.bikewalls.com/pictures/abc.jpg图像URL(未加载)javascript/jquery检查图像是否存在?
我需要一个JavaScript/jQuery函数/代码以警告说上述网址有效或not.These网址将作为参数传递。以上例为例,将会非常有帮助。
下面给出 http://www.bikewalls.com/pictures/abc.jpg图像URL(未加载)javascript/jquery检查图像是否存在?
我需要一个JavaScript/jQuery函数/代码以警告说上述网址有效或not.These网址将作为参数传递。以上例为例,将会非常有帮助。
您可以使用onload
和onerror
回调是这样的:
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;
FIDDLE:http://jsfiddle.net/473GV/
快速和使用简单的jQuery:
$("<img/>")
.load(function() {
console.log("image loaded correctly");
})
.error(function() {
alert("error loading image");
})
.attr("src", $(originalImage).attr("src"));
很明显,你必须适应这种变化这对你的具体情况,但你明白了。你可以阅读更多关于jQuery的$.error()
here。
你在哪里写这个函数卡住了? –
在[此前StackOverflow答案](http://stackoverflow.com/questions/9714525/javascript-image-url-verify/9714891#9714891)是一个函数称为'testImage()',它需要一个图像的URL来测试和会调用您的回调函数,并告诉您图像是否成功加载。 – jfriend00