'console'是Internet Explorer的未定义错误 [英] 'console' is undefined error for Internet Explorer
问题描述
我正在使用Firebug,并且有一些声明:
I'm using Firebug and have some statements like:
console.log("...");
在我的页面中。在IE8(也可能是早期版本)中,我收到脚本错误,说控制台未定义。我尝试将它放在页面顶部:
in my page. In IE8 (probably earlier versions too) I get script errors saying 'console' is undefined. I tried putting this at the top of my page:
<script type="text/javascript">
if (!console) console = {log: function() {}};
</script>
我仍然得到错误。有没有办法摆脱错误?
still I get the errors. Any way to get rid of the errors?
推荐答案
试试
if (!window.console) console = ...
未定义的变量不能直接引用。但是,所有全局变量都是全局上下文相同名称的属性(对于浏览器, window
),并且访问未定义的属性也没问题。
An undefined variable cannot be referred directly. However, all global variables are attributes of the same name of the global context (window
in case of browsers), and accessing an undefined attribute is fine.
或者使用 if(typeof console ==='undefined')console = ...
如果你想避免魔术变量 window
,请参阅 @Tim Down的回答。
Or use if (typeof console === 'undefined') console = ...
if you want to avoid the magic variable window
, see @Tim Down's answer.
这篇关于'console'是Internet Explorer的未定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!