如何检查图片是否存在给定的URL? [英] How to check if image exists with given url?

查看:156
本文介绍了如何检查图片是否存在给定的URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jquery检查图像是否存在.

I want to check if an image exists using jquery.

例如,我如何检查该图像是否存在

For example how do I check this image exists

http://www.google.com/images/srpr/nav_logo14.png 

支票必须给我200或状态还可以

the check must give me a 200 or status ok

--------------编辑-------------------

--------------edited-------------------

var imgsrc = $(this).attr('src');
var imgcheck = imgsrc.width;


if (imgcheck==0) {
alert("You have a zero size image");
} else { //do rest of code }

谢谢 吉恩

推荐答案

使用 error 这样的处理程序:

Use the error handler like this:

$('#image_id').error(function() {
  alert('Image does not exist !!');
});

如果无法加载图像(例如,由于所提供的URL中不存在该图像),则会显示警报:

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

更新:

我认为使用:

$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});

足以检查404.

更多读物:

  • http://www.jibbering.com/2002/4/httprequest.html
  • http://www.ibm.com/developerworks/web/library/wa-ajaxintro3/

更新2:

您的代码应如下所示:

$(this).error(function() {
  alert('Image does not exist !!');
});

不需要这些行,也不会检查远程文件是否存在:

No need for these lines and that won't check if the remote file exists anyway:

var imgcheck = imgsrc.width;    

if (imgcheck==0) {
  alert("You have a zero size image");
} else { 
  //execute the rest of code here 
}

这篇关于如何检查图片是否存在给定的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆