且构网

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

使用JavaScript测试图像是否正确加载

更新时间:2023-11-26 12:17:40

var image = new Image();
image.onload = function() {
   // display green arrow
}
image.onerror = function() {
   // display red arrow
}
image.src = 'http://yourserver/test.gif';

编辑:

由于HTML中已有图像,因此onerror事件不仅仅是DOM的HTML的一部分。从理论上讲,如果你不介意无效标记,你可以这样做:

With the images already in the HTML it becomes a bit tricky, because the onerror event is not part of HTML only of the DOM. Theoretically you could do something like this, if you don't mind invalid markup:

<img src="http://yourserver/up_arrow.png" onerror="this.src='down_arrow.png'">