2

我正在使用 try、catch 进行调试,但警告不会创建异常。如何获取所有 javascript 警告和错误以输出 div?

更新: 如果浏览器支持 Afaik 日志记录,如何将该日志转换为字符串或输出 div?

更新: 我找到了如何做到这一点的方法:我可以将 console.log 函数重新加载到我的自定义函数中,并调用本机 console.log 函数。

4

3 回答 3

0

首先,摆脱try catch。调试时不要使用 try catch。

其次,您不想将错误输出到 div,为此使用 firebug 或检查器 - console.log();

第三,如果你真的想这样做:你可以使用 try catch 和在 catch 中,使用类似的东西

$('body').append($('div').html('variable for error message goes here'));

如果您使用的是 jquery

或者

document.getElementByTagName("body").appendChild( document.createTextNode("variable for error message goes here") );

如果你有普通的 javascript

编辑:尝试查找即调试栏即 webDeveloper

于 2013-01-23T14:00:06.920 回答
0

我理解自己为什么有人可能希望在文档中出现错误时实际发生某些事情。上面的答案只是说您会使用开发人员工具,但我需要实际发生的事情,经过一番搜索,这就是我发现的......

如果您希望捕获所有出现的错误,您可以将以下代码放入您的文件中,最好放在顶部:

window.onerror = function(errorMsg, url, lineNumber){
    // any action you want goes here
    // errorMsg is the error message itself.
    // url should be the file presenting the error, though i have
    //    found that it only presents to me the address of the site.
    // lineNumber is the line number the error occoured on.
    // here is an example of what you could do with it:
    alert("Error in " + url + " at " + lineNumber + ":\n" + errorMsg);
}

我自己喜欢将错误输出到包含所有错误的 div,尽管您可以对这些信息执行任何操作,就像您可以对传递给函数的任何其他字符串执行的操作一样。

下面是一个示例,如果您使用上面的代码对按钮抛出错误,可能会发生什么:

your.site.here 中的错误 1:

未捕获的 ReferenceError:未定义 foo

于 2015-10-24T18:39:17.073 回答
-1

对于 IE javascript 调试,您可以按照以下指南进行操作:

http://msdn.microsoft.com/en-au/library/ie/gg699336(v=vs.85).aspx

请记住,开发人员工具窗口必须在加载页面之前打开,这样警告和错误才会出现在控制台中。

对于 webkit,(chrome, safari) 开发者控制台 - 这是一个指南:

https://developers.google.com/chrome-developer-tools/docs/console

...Firefox 也有一个控制台

于 2013-01-23T14:14:40.690 回答