给定以下图片链接:http://www.bikewalls.com/pictures/abc.jpg(无法加载)
我需要一个javascript/jquery函数/代码来警告是否上述链接有效。这些链接将作为参数传递。以上面的例子为例会非常有帮助。
给定以下图片链接:http://www.bikewalls.com/pictures/abc.jpg(无法加载)
我需要一个javascript/jquery函数/代码来警告是否上述链接有效。这些链接将作为参数传递。以上面的例子为例会非常有帮助。
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()
。
testImage()
的函数,它接受要测试的图像URL,并将调用您的回调并告诉您图像是否成功加载。 - jfriend00