使用 onerror 事件是传统的捕捉页面出错的方法。
—————————————————————————-
onerror 事件
我们前面介绍了怎样使用try…catch 语句来捕捉页面出错。 现在我们将介绍如何使用 onerror 事件来达到同样的目的。
当页面中出现错误时, onerror 事件就会被触发。
使用onerror事件, 你需要写一个函数来处理这些错误, 然后用onerror事件处理器(handler)调用这个函数。 这个事件处理器有三个参数:msg (出错信息), url (出错页面的url) 和 line (出错行号)。
语法
onerror=handleErrfunction handleErr(msg,url,l) { //出错处理 return true or false } |
onerror的返回值决定了浏览器是否显示一个标准出错信息。 如果你返回的是false,浏览器将在JavaScritp的console里显示标准出错信息。 如果返回true, 浏览器则不会显示标准出错信息。
例子
以下例子显示了如何用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> |