Javascript:console.log到html

leo*_*neo 53 javascript

我想将console.log输出写入div层.

例如:

document.write(console.log(5+1)); //Incorrect, random example
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决问题吗?

谢谢.

编辑:

我的意思是,例如:

console.log("hi");
Run Code Online (Sandbox Code Playgroud)

它在屏幕上显示输出"hi".

注意:一个例子:http://labs.codecademy.com/#:workspace

Aru*_*hny 82

您可以覆盖默认实现 console.log()

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function (message) {
        if (typeof message == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(message) : message) + '<br />';
        } else {
            logger.innerHTML += message + '<br />';
        }
    }
})();
Run Code Online (Sandbox Code Playgroud)

演示:小提琴

  • 除了继续使用默认的console.log功能外,添加'old(message);' 在新的console.log函数的末尾. (2认同)

Nit*_*... 24

@ arun-p-johny的答案略有改进:

在HTML中,

<pre id="log"></pre>
Run Code Online (Sandbox Code Playgroud)

在js中,

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function () {
      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';
        } else {
            logger.innerHTML += arguments[i] + '<br />';
        }
      }
    }
})();
Run Code Online (Sandbox Code Playgroud)

开始使用:

console.log('How', true, new Date());
Run Code Online (Sandbox Code Playgroud)

  • 为了保持原来的 `console.log` 功能,在新的控制台日志功能的末尾添加 `old(...arguments);`。请记住使用扩展运算符! (3认同)
  • `old.apply(console,arguments);`也可以保留原始参数. (2认同)
  • 我有点困惑,我对Javascript很陌生,这个函数的结构是什么。第一个括号,为什么?最后一个括号对是什么? (2认同)

Hri*_*dov 12

我对Arun P Johny的更高级版本的回答有点迟了.他的解决方案不处理多个参数,也不提供对原始函数的访问.console.log()

这是我的版本:

(function (logger) {
    console.old = console.log;
    console.log = function () {
        var output = "", arg, i;

        for (i = 0; i < arguments.length; i++) {
            arg = arguments[i];
            output += "<span class=\"log-" + (typeof arg) + "\">";

            if (
                typeof arg === "object" &&
                typeof JSON === "object" &&
                typeof JSON.stringify === "function"
            ) {
                output += JSON.stringify(arg);   
            } else {
                output += arg;   
            }

            output += "</span>&nbsp;";
        }

        logger.innerHTML += output + "<br>";
        console.old.apply(undefined, arguments);
    };
})(document.getElementById("logger"));

// Testing
console.log("Hi!", {a:3, b:6}, 42, true);
console.log("Multiple", "arguments", "here");
console.log(null, undefined);
console.old("Eyy, that's the old and boring one.");
Run Code Online (Sandbox Code Playgroud)
body {background: #333;}
.log-boolean,
.log-undefined {color: magenta;}
.log-object,
.log-string {color: orange;}
.log-number {color: cyan;}
Run Code Online (Sandbox Code Playgroud)
<pre id="logger"></pre>
Run Code Online (Sandbox Code Playgroud)

我把它一个微小的一点,并增加了一个类来每个日志,所以你可以颜色它.它输出Chrome控制台中显示的所有参数.您还可以访问旧日志console.old().

这是上面脚本的缩小版本,可以粘贴内联,仅供您使用:

<script>
    !function(o){console.old=console.log,console.log=function(){var n,e,t="";for(e=0;e<arguments.length;e++)t+='<span class="log-'+typeof(n=arguments[e])+'">',"object"==typeof n&&"object"==typeof JSON&&"function"==typeof JSON.stringify?t+=JSON.stringify(n):t+=n,t+="</span>&nbsp;";o.innerHTML+=t+"<br>",console.old.apply(void 0,arguments)}}
    (document.body);
</script>
Run Code Online (Sandbox Code Playgroud)

document.body在括号中替换您要登录的任何元素.


Ben*_*ema 9

派对晚了一点,但我对@Hristiyan Dodov的回答了一点。

现在,所有控制台方法都已重新连接,并且在文本溢出的情况下,包括可选的自动滚动到底部。现在,颜色基于记录方法而不是参数。

rewireLoggingToElement(
    () => document.getElementById("log"),
    () => document.getElementById("log-container"), true);

function rewireLoggingToElement(eleLocator, eleOverflowLocator, autoScroll) {
    fixLoggingFunc('log');
    fixLoggingFunc('debug');
    fixLoggingFunc('warn');
    fixLoggingFunc('error');
    fixLoggingFunc('info');

    function fixLoggingFunc(name) {
        console['old' + name] = console[name];
        console[name] = function(...arguments) {
            const output = produceOutput(name, arguments);
            const eleLog = eleLocator();

            if (autoScroll) {
                const eleContainerLog = eleOverflowLocator();
                const isScrolledToBottom = eleContainerLog.scrollHeight - eleContainerLog.clientHeight <= eleContainerLog.scrollTop + 1;
                eleLog.innerHTML += output + "<br>";
                if (isScrolledToBottom) {
                    eleContainerLog.scrollTop = eleContainerLog.scrollHeight - eleContainerLog.clientHeight;
                }
            } else {
                eleLog.innerHTML += output + "<br>";
            }

            console['old' + name].apply(undefined, arguments);
        };
    }

    function produceOutput(name, args) {
        return args.reduce((output, arg) => {
            return output +
                "<span class=\"log-" + (typeof arg) + " log-" + name + "\">" +
                    (typeof arg === "object" && (JSON || {}).stringify ? JSON.stringify(arg) : arg) +
                "</span>&nbsp;";
        }, '');
    }
}


setInterval(() => {
  const method = (['log', 'debug', 'warn', 'error', 'info'][Math.floor(Math.random() * 5)]);
  console[method](method, 'logging something...');
}, 200);
Run Code Online (Sandbox Code Playgroud)
#log-container { overflow: auto; height: 150px; }

.log-warn { color: orange }
.log-error { color: red }
.log-info { color: skyblue }
.log-log { color: silver }

.log-warn, .log-error { font-weight: bold; }
Run Code Online (Sandbox Code Playgroud)
<div id="log-container">
  <pre id="log"></pre>
</div>
Run Code Online (Sandbox Code Playgroud)


mač*_*ček 7

创建一个输出

<div id="output"></div>
Run Code Online (Sandbox Code Playgroud)

使用JavaScript写入它

var output = document.getElementById("output");
output.innerHTML = "hello world";
Run Code Online (Sandbox Code Playgroud)

如果您希望它处理更复杂的输出值,您可以使用 JSON.stringify

var myObj = {foo: "bar"};
output.innerHTML = JSON.stringify(myObj);
Run Code Online (Sandbox Code Playgroud)