【问题标题】:Is there a way to print the console log from JavaScript, into HTML?有没有办法将控制台日志从 JavaScript 打印到 HTML 中?
【发布时间】:2015-12-12 19:13:30
【问题描述】:

假设我有一些 JavaScript 函数,它在运行时会在控制台中记录其输出 - 使用 console.log()。函数运行后,有没有办法让它将结果导出到 HTML 控制台?

谢谢

【问题讨论】:

标签: javascript html console console.log


【解决方案1】:

您可以用自己的函数覆盖默认函数。

(function () {

    // save the original console.log function
    var old_logger = console.log;

    // grab html element for adding console.log output
    var html_logger = document.getElementById('html_logger');

    // replace console.log function with our own function
    console.log = function(msg) {

      // first call old logger for console output
      old_logger.call(this, arguments);

      // check what we need to output (object or text) and add it to the html element.
      if (typeof msg == 'object') {
        html_logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(msg) : msg) + '<br>';
      } else {
        html_logger.innerHTML += msg + '<br>';
      }
    }
})();

这是一个 JSFiddle,用一个工作示例来完成答案。

http://jsfiddle.net/djr0mj9p/1/

【讨论】:

    【解决方案2】:

    你可以扩展console.log函数:

    function extendLog(logger) {
        var original = console.log;
        console.log = function() {
            logger(Array.prototype.slice.call(arguments));
            return original.apply(this, arguments);
        }
    }
    
    // custom logger
    // args - array of arguments passed to console.log
    var myLogger = function(args) {
        var log = document.createElement("div");
        log.innerHTML = args;
        document.body.appendChild(log);
    }
    
    extendLog(myLogger);
    
    console.log("Hello world!");
    console.log("How", "are", "you?");
    

    extendLog 函数有一个参数,即您的日志记录函数。您还可以使用不同的记录器多次调用 extendLog。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 2014-09-23
      • 2011-03-07
      相关资源
      最近更新 更多