如何检查图像是否存在给定的URL?

时间:2010-08-01 10:34:08

标签: jquery

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

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

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

支票必须给我200或状态确定

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

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


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

由于 让

7 个答案:

答案 0 :(得分:75)

像这样使用error处理程序:

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

如果无法加载图像(例如,因为它不在提供的URL中),则会显示警告:

<强>更新

我认为使用:

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

足以检查404。

更多读物:

更新2:

您的代码应该是这样的:

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

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

var imgcheck = imgsrc.width;    

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

答案 1 :(得分:31)

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function(){
            //do something depressing
    },
    success: function(){
            //do something cheerful :)
    }
});

来自:http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06

答案 2 :(得分:11)

如果它不存在加载默认图像或处理错误

$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) {
    if (status == "error") 
        $(this).attr('src', 'images/DEFAULT.JPG');
    else
        $(this).attr('src', imgurl);
    });

答案 3 :(得分:4)

使用案例

$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"});

API:

$.fn.safeUrl=function(args){
  var that=this;
  if($(that).attr('data-safeurl') && $(that).attr('data-safeurl') === 'found'){
        return that;
  }else{
       $.ajax({
    url:args.wanted,
    type:'HEAD',
    error:
        function(){
            $(that).attr('src',args.rm)
        },
    success:
        function(){
             $(that).attr('src',args.wanted)
             $(that).attr('data-safeurl','found');
        }
      });
   }


 return that;
};

注意:rm表示风险管理。


另一个用例:

$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
  • &#39; http://example/1.png&#39; :如果不存在&#39; http://example/2.png&#39;

  • &#39; http://example/2.png&#39; :如果不存在&#39; http://example/3.png&#39;

答案 4 :(得分:3)

来自here

// when the DOM is ready
$(function () {
  var img = new Image();
  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();
      // with the holding div #loader, apply:
      $('#loader')
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .append(this);
      // fade our image in to create a nice effect
      $(this).fadeIn();
    })
    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
    })
    // *finally*, set the src attribute of the new image to our image
    .attr('src', 'images/headshot.jpg');
});

答案 5 :(得分:0)

jQuery 3.0 removed .error。现在是正确的语法

$(this).on('error', function(){
    console.log('Image does not exist: ' + this.id); 
});

答案 6 :(得分:0)

要处理图像存在的延迟加载,我在jQuery-

中遵循了
$('[data-src]').each(function() {
  var $image_place_holder_element = $(this);
  var image_url = $(this).data('src');
  $("<div class='hidden-classe' />").load(image_url, function(response, status, xhr) {
    if (!(status == "error")) {
      $image_place_holder_element.removeClass('image-placeholder');
      $image_place_holder_element.attr('src', image_url);
    }
  }).remove();
});

原因:如果我使用$image_place_holder_element.load()方法,它将在元素上添加响应,因此将div随机删除并将其删除似乎是一个很好的解决方案。希望它对尝试实现延迟加载以及url检查的用户有用。