我使用Firebug,并有一些语句像:

console.log("...");

在我的页面上。在IE8(可能是更早的版本),我得到脚本错误说“控制台”是未定义的。我试着把这个放在我页面的顶部:

<script type="text/javascript">
    if (!console) console = {log: function() {}};
</script>

我还是会得到错误。有办法消除错误吗?


当前回答

console = console || { 
    debug: function(){}, 
    log: function(){}
    ...
}

其他回答

Try

if (!window.console) console = ...

未定义的变量不能直接引用。但是,所有全局变量都是全局上下文(浏览器为窗口)同名的属性,访问未定义的属性是可以的。

或者使用if (typeof console === 'undefined') console =…如果你想避开神奇的变量窗口,请参阅@Tim Down的回答。

如果你在IE8中打开了开发人员工具,你可以使用Console .log(),也可以使用脚本选项卡上的控制台文本框。

console = console || { 
    debug: function(){}, 
    log: function(){}
    ...
}

You can use the below to give an extra degree of insurance that you've got all bases covered. Using typeof first will avoid any undefined errors. Using === will also ensure that the name of the type is actually the string "undefined". Finally, you'll want to add a parameter to the function signature (I chose logMsg arbitrarily) to ensure consistency, since you do pass whatever you want printed to the console to the log function. This also keep you intellisense accurate and avoids any warnings/errors in your JS aware IDE.

if(!window.console || typeof console === "undefined") {
  var console = { log: function (logMsg) { } };
}

我使用的是fauxconsole;我修改了css一点,使它看起来更好,但工作得很好。