我使用Firebug,并有一些语句像:
console.log("...");
在我的页面上。在IE8(可能是更早的版本),我得到脚本错误说“控制台”是未定义的。我试着把这个放在我页面的顶部:
<script type="text/javascript">
if (!console) console = {log: function() {}};
</script>
我还是会得到错误。有办法消除错误吗?
我使用Firebug,并有一些语句像:
console.log("...");
在我的页面上。在IE8(可能是更早的版本),我得到脚本错误说“控制台”是未定义的。我试着把这个放在我页面的顶部:
<script type="text/javascript">
if (!console) console = {log: function() {}};
</script>
我还是会得到错误。有办法消除错误吗?
当前回答
我使用的是fauxconsole;我修改了css一点,使它看起来更好,但工作得很好。
其他回答
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) { } };
}
要在IE中调试,请查看这个log4javascript
有时控制台可以在IE8/9中工作,但在其他时候会失败。这种不稳定的行为取决于你是否打开了开发工具,并在stackoverflow问题中描述了IE9是否支持console.log,这是一个真实的函数吗?
在IE9中,如果控制台未打开,以下代码:
alert(typeof console);
会显示“对象”,但这个代码
alert(typeof console.log);
将抛出TypeError异常,但不返回未定义的值;
因此,保证版本的代码将类似于:
try {
if (window.console && window.console.log) {
my_console_log = window.console.log;
}
} catch (e) {
my_console_log = function() {};
}
注意到OP在IE中使用Firebug,所以假设它是Firebug Lite。当调试器窗口打开时,在IE中定义控制台,这是一种奇怪的情况,但是当Firebug已经在运行时会发生什么呢?不确定,但在这种情况下,"firebugx.js"方法可能是一个很好的测试方法:
来源:
https://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=187
if (!window.console || !console.firebug) {
var names = [
"log", "debug", "info", "warn", "error", "assert",
"dir","dirxml","group","groupEnd","time","timeEnd",
"count","trace","profile","profileEnd"
];
window.console = {};
for (var i = 0; i < names.length; ++i)
window.console[names[i]] = function() {}
}
(更新链接12/2014)