IE8中控制台未定义问题

Console undefined issue in IE8

本文关键字:问题 未定义 控制台 IE8      更新时间:2023-09-26

我理解如果调试窗口打开,IE只将控制台作为对象。如果调试窗口未打开,则将console视为未定义。

这就是为什么我决定添加一个如果检查,像这样:

        if(console)
            console.log('removing child');

我的理解是,如果控制台是未定义的,它将跳过console.log。然而,在IE8的if(控制台)行通过,我得到一个未定义的异常,就像之前在console.log。这太奇怪了

有办法解决这个问题吗?如何在代码中编写控制台,使其在所有三种浏览器上都能运行?

您可以在if子句中添加以下内容:

if (console && console.log) {
    console.log('removing child');
}

或者像这样为console.log函数编写一个日志包装器。

window.log = function () {
    if (this.console && this.console.log) {
        this.console.log(Array.prototype.slice.call(arguments));
    }
}

像这样使用:

log("This method is bulletproof", window, arguments");

下面是一个示例:http://jsfiddle.net/joquery/4Ugvg/

可以将console.log设置为空函数

if(typeof console === "undefined") {
    console = {
        log : function () {}
    }
}

检查控制台是否存在

window.console && console.log('foo');

尝试使用这样的条件,因为如果不支持console,它将抛出undefined not false;

if(typeof console !== "undefined") {
console.log('removing child');
}

然而,为了避免必须包装所有的控制台日志语句,我将把这段代码片段放在代码中。这将阻止IE抛出任何错误

if(typeof console === "undefined") {
    console = {
        log: function() { },
        debug: function() { },
        ...
    };
}

您需要检查控制台的类型,以及console.log的类型。你可能想检查这个链接:

console.log在IE8中发生了什么?

查看更多信息:http://patik.com/blog/complete-cross-browser-console-log/