javascript 检查 img src 是否有效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3499941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:55:38  来源:igfitidea点击:

javascript check if img src is valid?

javascriptimagesrc

提问by kiasecto

I have something like:

我有类似的东西:

document.getElementById('MyPicture').src = 'attempted.png';

If the client cannot get that resource, I would like to replace it with:

如果客户端无法获得该资源,我想将其替换为:

document.getElementById('MyPicture').src = 'error.png'

I know I can put onError=function() in the image tag, but how can I pass the Id to onError, so that I can have one onError function that can change the src of any bad pics?

我知道我可以将 onError=function() 放在图像标签中,但是如何将 Id 传递给 onError,以便我可以拥有一个可以更改任何不良图片的 src 的 onError 函数?

回答by CMS

Yes, you can use the onerrorevent, on image elements is really widely supported, for example:

是的,您可以使用该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';

Check an example here. ?

在此处查看示例。?

回答by kiasecto

Put this in the image tag:

把它放在图像标签中:

onError="image_error(this.id)"

which will pass the id of the image to image_error function.... duh

它将图像的 id 传递给 image_error 函数....废话

回答by Raul Agrait

Adding the onError attribute is indeed the correct way to handle it. In your case, you'd add something like:

添加 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';
}