【问题标题】:How to check if image exists with given url?如何使用给定的网址检查图像是否存在?
【发布时间】:2023-03-22 01:48:01
【问题描述】:

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

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

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

支票必须给我一个 200 或状态 ok

-------------已编辑-------

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


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

谢谢 让

【问题讨论】:

  • 您完全有权发布和接受您自己问题的答案。

标签: jquery


【解决方案1】:

像这样使用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 
}

【讨论】:

  • @sAc 我没有图像的 id,只是想检查文件是否存在,否则继续执行剩余的代码
  • @Jean:请在您的问题中发布您的代码,看看您有什么或如何需要它。
  • 如果你看看这个 url google.com/images/srpr/nav_logo14.png ,如果图像存在,它必须给我尺寸,或者状态 200/ok
  • @sAc imgsrc.width 似乎不起作用。我正在使用图像 url 来获取宽度...图像 url 正在传递,通过警报检查
  • 在大多数情况下,您需要将 async:false 添加到 AJAX 调用中,否则它将以某个随机间隔返回,并可能导致您的脚本产生不稳定的结果。
【解决方案2】:
$.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

【讨论】:

  • 警告:你会得到错误:[XMLHttpRequest 无法加载not.on.your.domain.com/someimg.jpg。请求的资源上不存在“Access-Control-Allow-Origin”标头。] 因此,如果图像在您的服务器上,这只是一个不错的选择。
【解决方案3】:

如果不存在则加载默认图片或处理错误

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

【讨论】:

  • 这是正确答案,你也可以使用$('<img>').load(url ...
【解决方案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"});
  • 'http://example/1.png' : 如果不存在 'http://example/2.png'

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

【讨论】:

    【解决方案5】:

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

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

        【解决方案7】:

        为了处理带有图像存在检查的延迟加载,我在 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 检查的人。

        【讨论】:

          猜你喜欢
          • 2018-09-17
          • 2011-03-20
          • 2021-06-20
          • 2014-07-10
          • 2011-11-20
          • 2017-04-12
          • 1970-01-01
          • 1970-01-01
          • 2014-01-16
          相关资源
          最近更新 更多