JavaScript/jQuery如何检查图片是否存在?

3

给定以下图片链接:http://www.bikewalls.com/pictures/abc.jpg(无法加载)

我需要一个javascript/jquery函数/代码来警告是否上述链接有效。这些链接将作为参数传递。以上面的例子为例会非常有帮助。


1
你在编写这个函数时卡住了吗? - David Thomas
1
这个之前的StackOverflow答案中有一个名为testImage()的函数,它接受要测试的图像URL,并将调用您的回调并告诉您图像是否成功加载。 - jfriend00
2个回答

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;

FIDDLE: http://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()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接