Javascript:图像对象的onerror事件有哪些参数?如何获取与图像相关的错误的其他详细信息? [英] Javascript: Which parameters are there for the onerror event with image objects? How to get additional details on an error related to an image?
问题描述
我正在用JavaScript编写一个应会创建新图像的应用程序.有时会失败.通过附加image.onerror
事件侦听器,我能够检测出它的运行时间.问题是:如何得知发生了什么错误-错误对象为图像带来了哪些参数?到目前为止,我只发现了
I'm writing an application in JavaScript that should create a new image. Sometimes it fails. I was able to detect the times when it does by attaching an image.onerror
event listener. Question is: How may I learn what error occured - what parameters does the error object for images bring? So far I only found out that
image.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
console.log('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber
+ ' Column: ' + column + ' StackTrace: ' + errorObj);
}
我来自: javascript:如何在弹出警报中显示脚本错误?
返回Error: [object Event] Script: undefined Line: undefined Column: undefined StackTrace: undefined
,并且在错误对象中我找不到与消息或错误代码相关的任何内容.
returns Error: [object Event] Script: undefined Line: undefined Column: undefined StackTrace: undefined
and in the error object I couldn't find anything related to message or error code.
推荐答案
如果您想在常规HTML img
元素上捕获错误(而不是通过DOM动态创建一个元素),这似乎很好用:>
If you want to trap errors on a normal HTML img
element (rather than dynamically creating one via the DOM), this seems to work well:
<img src="http://yourdomain/site/badimage.png"
onerror="javascript:imageErrorHandler.call(this, event);"/>
请注意,.call(this, event)
语法很重要,因此您可以访问错误处理程序中的this
和event
对象.
Note that the .call(this, event)
syntax is important so you have access to the this
and event
objects in your error handler.
然后,您可以定义一个图像错误处理程序,如下所示. (确保在img
元素之前定义它以避免竞争情况.)假设您已连接jQuery:
Then you can define an image error handler like the following. (Make sure it is defined before the img
element to avoid race conditions.) Assuming you have jQuery wired up:
function imageErrorHandler(evt) {
var $e = $(this);
var src = $e.attr("src");
console.log("Image URL '" + src + "' is invalid.");
};
在Chrome中对此进行了测试.没有尝试过其他浏览器.
Tested this in Chrome. Have not tried other browsers.
这篇关于Javascript:图像对象的onerror事件有哪些参数?如何获取与图像相关的错误的其他详细信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!