Mar*_*son 433 javascript debugging
如何将消息打印到错误控制台,最好包括变量?
例如,类似于:
print('x=%d', x);
Run Code Online (Sandbox Code Playgroud)
Dan*_*Dan 465
安装Firebug,然后您可以使用console.log(...)
和console.debug(...)
等(有关更多信息,请参阅文档).
Nic*_*las 312
console.error(message); //gives you the red errormessage
console.log(message); //gives the default message
console.warn(message); //gives the warn message with the exclamation mark in front of it
console.info(message); //gives an info message with an 'i' in front of the message
Run Code Online (Sandbox Code Playgroud)
您还可以将CSS添加到日志消息中:
console.log('%c My message here', "background: blue; color: white; padding-left:10px;");
Run Code Online (Sandbox Code Playgroud)
Ivo*_*lka 86
异常将记录到JavaScript控制台中.如果您想要禁用Firebug,可以使用它.
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0);
}
Run Code Online (Sandbox Code Playgroud)
用法:
log('Hello World');
log('another message');
Run Code Online (Sandbox Code Playgroud)
Ian*_*ley 55
调试JavaScript:抛出警报,概述了跨浏览器工作的一种好方法!.
小智 15
如果你使用Safari,你可以写
console.log("your message here");
Run Code Online (Sandbox Code Playgroud)
它出现在浏览器的控制台上.
dla*_*rte 14
这是一个关于如何将消息打印到浏览器的错误控制台而不是调试器控制台的文字问题的解决方案.(可能有充分的理由绕过调试器.)
正如我在评论中提到的,在错误控制台中抛出错误以获取消息的建议时,一个问题是这将中断执行的线程.如果您不想中断该线程,可以将错误抛出到一个单独的线程中,一个使用setTimeout创建.因此我的解决方案(原来是Ivo Danihelka的一个阐述):
var startTime = (new Date()).getTime();
function logError(msg)
{
var milliseconds = (new Date()).getTime() - startTime;
window.setTimeout(function () {
throw( new Error(milliseconds + ': ' + msg, "") );
});
}
logError('testing');
Run Code Online (Sandbox Code Playgroud)
我包括自开始时间以来的时间(以毫秒为单位),因为超时可能会使您希望看到消息的顺序发生偏差.
Error方法的第二个参数是文件名,这里是一个空字符串,以防止输出无用的文件名和行号.可以获得调用者函数,但不能以简单的浏览器独立方式.
如果我们可以使用警告或消息图标而不是错误图标显示消息,那将是很好的,但我找不到这样做的方法.
使用throw的另一个问题是它可能被一个封闭的try-catch捕获并抛弃,并且将throw放在一个单独的线程中也避免了这个障碍.但是,还有另一种方法可以捕获错误,即window.onerror处理程序被替换为执行不同操作的处理程序.在那里帮不了你.
要真正回答这个问题:
console.error('An error occurred!');
console.error('An error occurred! ', 'My variable = ', myVar);
console.error('An error occurred! ' + 'My variable = ' + myVar);
Run Code Online (Sandbox Code Playgroud)
您也可以使用信息,日志或警告,而不是错误.
关于上面提到的'throw()'的说明.它似乎完全停止了页面的执行(我在IE8中检查过),所以它对于记录"正在进行的进程"(比如跟踪某个变量......)并不是很有用.
我的建议可能是在文档的某处添加一个textarea元素,并在需要时更改(或附加)其值(可以更改其文本)以记录信息...
与往常一样,Internet Explorer是旱冰鞋中的大象,只是简单地使用它就会阻止你console.log()
.
jQuery的日志可以很容易地进行调整,但是不得不在任何地方添加它.如果你正在使用jQuery的一个解决方案是在最后将它放入你的jQuery文件中,首先缩小:
function log()
{
if (arguments.length > 0)
{
// Join for graceful degregation
var args = (arguments.length > 1) ? Array.prototype.join.call(arguments, " ") : arguments[0];
// This is the standard; Firebug and newer WebKit browsers support this.
try {
console.log(args);
return true;
} catch(e) {
// Newer Opera browsers support posting erros to their consoles.
try {
opera.postError(args);
return true;
}
catch(e)
{
}
}
// Catch all; a good old alert box.
alert(args);
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
854934 次 |
最近记录: |