JS onerror

来源:互联网 发布:mysql执行多条sql文件 编辑:程序博客网 时间:2024/04/29 10:46

Using the onerror event is the old standard solution to catch errors in a web page.
使用onerror事件是捕捉web页错误的比较老的标准方法。


Examples
例子

The onerror event[onerror事件]
How to use the onerror event to catch errors in a web page.
使用的方法演示


The onerror Event

We have just explained how to use the try...catch statement to catch errors in a web page. Now we are going to explain how to use the onerror event for the same purpose.
我们已经解释怎样使用try...catch声明来获取web页的错误。现在我们将接着介绍怎样用onerror来达到相同的目的。

The onerror event is fired whenever there is a script error in the page.
不论什么时候只要脚本出现错误onerror事件就会被激活

To use the onerror event, you must create a function to handle the errors. Then you call the function with the onerror event handler. The event handler is called with three arguments: msg (error message), url (the url of the page that caused the error) and line (the line where the error occurred).
要使用onerror事件,你必须建立一个函数来处理错误。msg(错误信息),url(出错页的url)和line(发生错误的位置)

Syntax语法

onerror=handleErr
function handleErr(msg,url,l)
{
//Handle the error here
return true or false
}

The value returned by onerror determines whether the browser displays a standard error message. If you return false, the browser displays the standard error message in the JavaScript console. If you return true, the browser does not display the standard error message.
返回值决定是否在浏览器上显示标准的错误信息。如果你返回false,浏览器显示在JS控制台中的错误信息。如果你返回true,浏览器不显示错误信息。

Example举例

The following example shows how to catch the error with the onerror event:
下面的例子演示怎样用onerror事件来捕捉错误:

<html>
<head>
<script type="text/javascript">

onerror=handleErr
var txt=""
function handleErr(msg,url,l)
{
txt="There was an error on this page./n/n"
txt+="Error: " + msg + "/n"
txt+="URL: " + url + "/n"

txt+="Line: " + l + "/n/n"
txt+="Click OK to continue./n/n"
alert(txt)
return true
}
function message()
{
adddlert("Welcome guest!")
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>

 
原创粉丝点击