Javascript: console. log to html

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

例如:

document.write(console.log(5+1)); //Incorrect, random example

有人能给我一个解决问题的办法吗?

谢谢你。

编辑:

我的意思是,比如说:

console.log("hi");

它在屏幕上显示输出“ hi”。

注: 示例: http://labs.codecademy.com/#:workspace

152419 次浏览

可以重写 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 />';
}
}
})();

演示: 小提琴

创建一个输出

<div id="output"></div>

使用 JavaScript 写入它

var output = document.getElementById("output");
output.innerHTML = "hello world";

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

var myObj = {foo: "bar"};
output.innerHTML = JSON.stringify(myObj);

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

在 html 中,

<pre id="log"></pre>

在 J,

(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 />';
}
}
}
})();

开始使用:

console.log('How', true, new Date());

我带着更高级的 Arun P Johnny 的回答版本来到 有一点晚了。他的解决方案不能处理多个 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.");
body {background: #333;}
.log-boolean,
.log-undefined {color: magenta;}
.log-object,
.log-string {color: orange;}
.log-number {color: cyan;}
<pre id="logger"></pre>

I took it a tiny bit further and added a class to each log so you can color it. It outputs all arguments as seen in the Chrome console. You also have access to the old log via console.old().

Here's a minified version of the script above to paste inline, just for you:

<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>

用您希望登录的任何元素替换括号中的 document.body

虽然有点晚了,但我还是把 @ 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);
#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; }
<div id="log-container">
<pre id="log"></pre>
</div>

这篇文章对我帮助很大,经过几次迭代之后,我们使用的就是这个。

其思想是将日志消息和错误发布到 HTML,例如,如果您需要调试 JS 并且无法访问控制台。

您确实需要用“ logThis”更改“ console.log”,因为不推荐更改本机功能。

你会得到:

  • 一个简单明了的“ logThis”函数,它将显示字符串和对象 每行的当前日期和时间
  • 一个专门的窗口在其他所有事情之上。(只有在需要的时候才显示它)
  • 可以在“ . catch”中查看承诺中的相关错误。
  • 没有改变默认的 console.log 行为
  • 消息也将出现在控制台中。

function logThis(message) {
// if we pass an Error object, message.stack will have all the details, otherwise give us a string
if (typeof message === 'object') {
message = message.stack || objToString(message);
}


console.log(message);


// create the message line with current time
var today = new Date();
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
var time = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
var dateTime = date + ' ' + time + ' ';


//insert line
document.getElementById('logger').insertAdjacentHTML('afterbegin', dateTime + message + '<br>');
}


function objToString(obj) {
var str = 'Object: ';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '::' + obj[p] + ',\n';
}
}
return str;
}


const object1 = {
a: 'somestring',
b: 42,
c: false
};


logThis(object1)
logThis('And all the roads we have to walk are winding, And all the lights that lead us there are blinding')
#logWindow {
overflow: auto;
position: absolute;
width: 90%;
height: 90%;
top: 5%;
left: 5%;
right: 5%;
bottom: 5%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 20;
}
<div id="logWindow">
<pre id="logger"></pre>
</div>

也谢谢 这个答案,JSON.stringify ()对此没有起作用。

复制并粘贴下面的代码

console.log = (...e) => {for(var i=0;i<e.length;i++){document.getElementById("log").innerHTML += (typeof(e[i]) == "object" ? JSON.stringify(e[i]):e[i]) + "<br />"}};

console.log = (...e) => {for(var i=0;i<e.length;i++){document.getElementById("log").innerHTML += (typeof(e[i]) == "object" ? JSON.stringify(e[i]):e[i]) + "<br />"}};


console.log("Hello world",{objectWorks:true},["Array works?","Yes"])
<div id="log"></div>

If you would like to have the default "console.log", just change the "console.log" to "var CustomNameOfLog". Or Just copy & paste the code below.

var CustomNameOfLog = (...e) => {for(var i=0;i<e.length;i++){document.getElementById("log").innerHTML += (typeof(e[i]) == "object" ? JSON.stringify(e[i]):e[i]) + "<br />"}};

var customNameOfLog = (...e) => {for(var i=0;i<e.length;i++){document.getElementById("log").innerHTML += (typeof(e[i]) == "object" ? JSON.stringify(e[i]):e[i]) + "<br />"}};


customNameOfLog("Hello world",{objectWorks:true},["Array works?","Yes"])
<div id="log"></div>