我使用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>
我还是会得到错误。有办法消除错误吗?
当前回答
console = console || {
debug: function(){},
log: function(){}
...
}
其他回答
if (typeof console == "undefined") {
this.console = {
log: function() {},
info: function() {},
error: function() {},
warn: function() {}
};
}
您可以在Firefox中直接使用console.log(…),但不能在ie中使用。在ie中,你必须使用window.console。
另一种选择是typeof操作符:
if (typeof console == "undefined") {
this.console = {log: function() {}};
}
还有一种替代方法是使用日志库,比如我自己的log4javascript。
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一点,使它看起来更好,但工作得很好。