[英]Generate a random word from an array and then print it to the console log in a function in javascript
[英]Is there a way to print the console log from JavaScript, into HTML?
說我有一些JavaScript函數,該函數在運行時會使用console.log()
在控制台中記錄其輸出。 函數運行后,是否有辦法將結果導出到HTML控制台?
謝謝
您可以使用自己的功能覆蓋默認功能。
(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,通過一個工作示例來完善答案。
您可以擴展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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.