jQuery 如何检查给定网址的图像是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3381663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:20:57  来源:igfitidea点击:

How to check if image exists with given url?

jquery

提问by X10nD

I want to check if an image exists using jquery.

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

For example how do I check this image exists

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

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

the check must give me a 200 or status ok

支票必须给我 200 或状态 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 }

Thanks Jean

谢谢让

采纳答案by Sarfraz

Use the errorhandler like this:

error像这样使用处理程序:

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

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

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

Update:

更新:

I think using:

我认为使用:

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

would be enough to check for a 404.

足以检查 404。

More Readings:

更多阅读:

Update 2:

更新 2:

Your code should be like this:

你的代码应该是这样的:

$(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 
}

回答by Helmut

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

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

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

回答by kiev

if it doesnt exist load default image or handle error

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

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

回答by Abdennour TOUMI

Use Case

用例

$('#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;
};


Note : rmmeans here risk managment .

注:rm此处指风险管理。



Another Use Case :

另一个用例:

$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
  • 'http://example/1.png' : if not exist 'http://example/2.png'

  • 'http://example/2.png' : if not exist 'http://example/3.png'

  • ' http://example/1.png' : 如果不存在 ' http://example/2.png'

  • ' http://example/2.png' : 如果不存在 ' http://example/3.png'

回答by sje397

From 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');
});

回答by bjornte

jQuery 3.0 removed.error. Correct syntax is now

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

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

回答by Vishal Kumar Sahu

To handle the lazy loading with image existence check I followed this in jQuery-

为了通过图像存在检查处理延迟加载,我在 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();
});

Reason: if I am using $image_place_holder_element.load()method it will be adding the response to the element, so random div and removing it appeared me a good solution. Hope it works for someone trying to implement lazy loading along with url check.

原因:如果我使用$image_place_holder_element.load()方法,它将向元素添加响应,因此随机 div 并删除它对我来说是一个很好的解决方案。希望它适用于尝试实现延迟加载和 url 检查的人。