且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果文件存在,则更改图像源

更新时间:2022-12-06 07:38:09

你不必使用AJAX来这样做,因为您可以没有任何限制地热链接来自其他域的图像。以下是检查图像是否存在的方法:

You don't have to use AJAX to do this, since you can hot-link images from other domains without any restrictions. Here's how you can check if an image exists:

function checkImage(src) {
  var img = new Image();
  img.onload = function() {
    // code to set the src on success
  };
  img.onerror = function() {
    // doesn't exist or error loading
  };

  img.src = src; // fires off loading of image
}

这是一个有效的实现 http://jsfiddle.net/jeeah/