【问题标题】:Console undefined issue in IE8 [duplicate]IE8中的控制台未定义问题[重复]
【发布时间】:2013-06-10 21:03:55
【问题描述】:

我了解 IE 仅在调试窗口打开时将 console 视为对象。如果调试窗口未打开,则将控制台视为未定义。

这就是为什么我决定像这样添加 if 检查:

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

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

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

【问题讨论】:

  • 控制台在 IE8 中不支持,删除它在 FF,chrome,safari,iE9 中工作
  • @JamesDonnelly 您应该再次阅读该问题。不是 IE 中没有定义控制台,而是 IE8 中没有定义 console.log。

标签: javascript internet-explorer-8


【解决方案1】:

您可以在 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");

这是一个 jsfiddle: http://jsfiddle.net/joquery/4Ugvg/

【讨论】:

  • 这应该记录一个数组,为什么不将切片参数应用于console.log
  • +1 我遇到了 IE8 的问题并快速帮助我!
【解决方案2】:

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

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

这样你只需要麻烦一次。l

【讨论】:

    【解决方案3】:

    只要检查控制台是否存在

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

    【讨论】:

      【解决方案4】:

      尝试使用这样的条件,如果不支持控制台,它会抛出 undefined not false;

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

      但是,为了避免包装所有控制台日志状态,我只需将这个 sn-p 放入您的代码中。这将阻止 IE 抛出任何错误

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

      【讨论】:

        【解决方案5】:

        你需要检查console的类型是什么,以及console.log的类型是什么。您可能需要查看此链接:

        What happened to console.log in IE8?

        【讨论】:

          【解决方案6】:

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-07-06
            • 2016-02-02
            • 2023-04-08
            • 2015-06-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多