问题 javascript检查img src是否有效? [重复]


这个问题在这里已有答案:


4968
2017-08-17 06:46


起源



答案:


是的,你可以使用 onerror 事件,关于图像元素是真的 广泛支持, 例如:

var image = document.getElementById('MyPicture');
image.onerror = function () {
  alert('error loading ' + this.src);
  this.src = 'error.png'; // place your error.png image instead
};

image.src = 'non-existing.jpg';

检查一个例子 这里


13
2017-08-17 06:53





把它放在图片标签中:

onError="image_error(this.id)"

这会将图像的id传递给image_error函数.... duh


2
2017-08-17 06:55





添加onError属性确实是处理它的正确方法。在你的情况下,你会添加如下内容:

var myPicture = document.getElementById('MyPicture');
myPicture.onError = errorHandler();

function errorHandler(msg,file_loc,line_num) {
  myPicture.src = 'http://www.google.com/intl/en_ALL/images/srpr/logo1w.png';
}

1
2017-08-17 06:53