图像存在检查不起作用

时间:2013-08-22 05:12:46

标签: javascript

我使用了来自here的图片存在检查代码。我的代码如下:

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

但即使图像存在于给定路径上,每次出现错误。当我使用this URL时,既没有错误也没有成功回调。做错了什么?

2 个答案:

答案 0 :(得分:1)

您可以使用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
      },
   });
}

答案 1 :(得分:1)

试试这个

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");