2010-08-17 95 views
11

我有类似:javascript检查img src是否有效?

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

如果客户不能获取资源,我想用来替换:

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

我知道我可以把的onError =()函数的图像标记,但我怎样才能将Id传递给onError,以便我可以使用一个onError函数来更改任何不良图片的src?

回答

1

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

是的,你可以使用onerror事件,对图像元素确实是widely supported,例如:

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'; 

检查为例here

2

把这个图像标签:

onError="image_error(this.id)" 

将通过图像的ID image_error功能....咄