根据这篇文章,它在测试版中,但它不在发行版中?


当前回答

如果你所有的console.log调用都是“undefined”,这可能意味着你仍然加载了一个旧的firebuglite (firebug.js)。它将覆盖IE8的console.log的所有有效函数,即使它们确实存在。这就是发生在我身上的事。

检查重写控制台对象的其他代码。

其他回答

我真的很喜欢“orange80”发布的方法。它很优雅,因为你可以设置一次,然后忘记它。

其他方法要求您做一些不同的事情(每次调用console.log()以外的东西),这只是在自找麻烦……我知道我最终会忘记。

我更进一步,通过将代码包装在一个实用函数中,您可以在javascript的开头调用一次,只要是在任何日志记录之前。(我正在我公司的事件数据路由器产品中安装这个。这将有助于简化新管理界面的跨浏览器设计。)

/**
 * Call once at beginning to ensure your app can safely call console.log() and
 * console.dir(), even on browsers that don't support it.  You may not get useful
 * logging on those browers, but at least you won't generate errors.
 * 
 * @param  alertFallback - if 'true', all logs become alerts, if necessary. 
 *   (not usually suitable for production)
 */
function fixConsole(alertFallback)
{    
    if (typeof console === "undefined")
    {
        console = {}; // define it if it doesn't exist already
    }
    if (typeof console.log === "undefined") 
    {
        if (alertFallback) { console.log = function(msg) { alert(msg); }; } 
        else { console.log = function() {}; }
    }
    if (typeof console.dir === "undefined") 
    {
        if (alertFallback) 
        { 
            // THIS COULD BE IMPROVED… maybe list all the object properties?
            console.dir = function(obj) { alert("DIR: "+obj); }; 
        }
        else { console.dir = function() {}; }
    }
}

它适用于IE8。点击F12打开IE8的开发者工具。

>>console.log('test')
LOG: test

假设你不关心提醒的备用方法,这里有一个更简洁的方法来解决ie的缺点:

var console=console||{"log":function(){}};

更好的退路是:


   var alertFallback = true;
   if (typeof console === "undefined" || typeof console.log === "undefined") {
     console = {};
     if (alertFallback) {
         console.log = function(msg) {
              alert(msg);
         };
     } else {
         console.log = function() {};
     }
   }

答案太多了。我的解决方案是:

globalNamespace.globalArray = new Array();
if (typeof console === "undefined" || typeof console.log === "undefined") {
    console = {};
    console.log = function(message) {globalNamespace.globalArray.push(message)};   
}

简而言之,如果console.log不存在(或者在本例中没有打开),则将日志存储在全局名称空间数组中。这样,您就不会受到数百万条警报的困扰,并且仍然可以在打开或关闭开发人员控制台的情况下查看日志。