图像存在性检查不起作用

Image existance checking is not working

本文关键字:不起作用 检查 存在 图像      更新时间:2023-09-26

我在这里使用了图像存在性检查代码。我的代码看起来像:

var checkImage = function(src,success) {
  var img = new Image();
  img.onload = function() {
    success(src);
  };
  img.onerror = function() {
    alert('error');
  };
  img.src = src; // fires off loading of image
};

我称之为

var src='';
checkImage('../images/icon64x64.png',function(source){
  alert('success image'+source);
  src=source;
});

但每次它都会给出一个错误,即使图像存在于给定的路径上。当我使用这个URL时,既没有调用错误回调,也没有调用成功回调。什么地方做得不对?

尝试这个

function IsValidImageUrl(url) {
    $("<img>", {
    src: url,
    error: function() { alert(url + ': ' + false); },
    load: function() { alert(url + ': ' + true); }
  });
}
IsValidImageUrl("https://www.google.com/logos/2012/hertz-2011-hp.gif");
IsValidImageUrl("http://google.com");

您可以使用jquery检查文件是否存在

var checkImage=function(src){
   $.ajax({
      url:src,
      type: "HEAD",
      async: true,
      success: function()
      { 
         //This shows file is there
         // If it is there load it into your variable
      },
      error: function()
      {
       //file is not there
      },
   });
}