分享一个自定义的console类 让你不再纠结JS中的调试代码的兼容


Posted in Javascript onApril 20, 2012

问题的产生

在写JS的过程中,为了调试我们常常会写很多 console.log、console.info、console.group、console.warn、console.error代码来查看JS的运行情况,但发布时又因为IE不支持console,又要去掉这些代码,一不小心就会出错。

本文分享自己昨晚写的一个console类来试图解决这一问题。当然,更好的做法是把测试代码分开写,那样就不会有这个问题。

解决思路

如何解决IE下不兼容的问题呢,那就是我们自己定义一个console类来覆盖浏览器提供的console功能,这样只要在页面中引用此JS文件就可以了。

另外,此类还提供了查看输出的调试信息功能,console 定义了哪些功能呢,我们可以在这里看到:http://getfirebug.com/wiki/index.php/Console_API,我们可以看到这里提供了很多方法,我们常用的有 console.log、console.info、console.group、console.warn、console.error、console.profile、console.time,最后两个是分析代码性能的,比较复杂,本文没有实现。
代码解析

第一步,当然是搭一个结构,覆盖浏览器(firebug、chrome)提供的console功能,这样直接引用此JS文件即可保证浏览器(主要是IE)中不出错:

console var console={ 
assert:function(){ 
}, 
clear:function(){ 
}, 
count:function(){ 
}, 
debug:function(){ 
}, 
dir:function(){ 
}, 
dirxml:function(){ 
}, 
error:function(){ 
}, 
exception:function(){ 
}, 
group:function(name){ 
}, 
groupCollapsed:function(){ 
}, 
groupEnd:function(){ 
}, 
info:function(){ 
}, 
log:function(){ 
}, 
memoryProfile:function(){ 
}, 
memoryProfileEnd:function(){ 
}, 
profile:function(){ 
}, 
profileEnd:function(){ 
}, 
table:function(){ 
}, 
time:function(){ 
}, 
timeEnd:function(){ 
}, 
timeStamp:function(){ 
}, 
trace:function(){ 
}, 
warn:function(){ 
} 
};

第二步,实现 console.log方法。在所实现的几个方法中这个是最复杂的。

从firebug的API中我们可以看到,console.log不仅仅可以输出信息,还提供了类似 string.Format的功能,直接引用原文如下:

Here is the complete set of patterns that you may use for string substitution:

Pattern Type
 %s String
 %d, %i Integer (numeric formatting is not yet supported)
 %f Floating point number (numeric formatting is not yet supported)
 %o Object hyperlink
 %c Style formatting
其中的%c比较特殊,是给输出添加样式的,比如我们在firebug中这样写:
console.log('%cTest output', 'color:white; background-color:blue');

运行后的结果是这样的:

分享一个自定义的console类 让你不再纠结JS中的调试代码的兼容

这里%c也可以跟 %s、%d等混用。

所以,在代码中我直接用replace进行替换,由于JS中的replace默认只替换第一个匹配项,这里刚好,代码如下:

var args=Array.prototype.slice.call(arguments); 
if(args.length>1){ 
var i=1,hasstyle=false; 
if(args[0].indexOf("%c")==0){ 
args[0]=args[0].replace(/%c/,""); 
i=2; 
hasstyle=true; 
} 
for(;i<args.length;i++){ 
if(/%s|%d|%i|%o/.test(args[0])){ 
args[0]=args[0].replace(/%s|%d|%i|%o/,args[i]); 
} 
else{ 
break; 
} 
} 
if(i<args.length){ 
args[0]=args[0]+" "+args.slice(i).join(" "); 
} 
if(hasstyle){ 
consoleHelper.showlog(args[0],args[1]); 
} 
else{ 
consoleHelper.showlog(args[0]); 
} 
} 
else if(args.length==1){ 
if(arguments[0] instanceof Array){ 
consoleHelper.showlog("["+args[0]+"]"); 
} 
else if(arguments[0] instanceof Function){ 
consoleHelper.showlog(args[0],null,"console_log_function"); 
} 
else{ 
consoleHelper.showlog(args[0]); 
} 
} 
else{ 
consoleHelper.showlog(""); 
}

由于console.log可以接受多个参数,且个数不确定,所以这里直接没有写形参。对于%c虽然firebug中写在中间也是有效的,这里为了简单直接只对写在开头的有效。代码中先把参数转换为数组,然后对数组进行分情况处理。

当参数个数大于1时,对后面的参数用replace进行替换,然后把剩下的参数连接(join)起来进行输出。

当参数个数为1时,还要分两种情况,一是数组,二是方法。对于数组,按firebug中的格式,在两端加中括号,对于函数,把字的颜色变为绿色

当参数个数为0时,直接输出空字符串

后面的consoleHelper.showlog是为了输出方便另外写的一个方法,在这个方法中把各种调试信息的结果显示在页面上的一个div(如果存在)中。

其他几个方法的思路跟这个差不多,只是样式不同,功能比这个简单,直接把参数连接起来输出即可。

整个console类代码如下:

console全部代码 var console={ 
assert:function(){ 
}, 
clear:function(){ 
}, 
count:function(){ 
}, 
debug:function(){ 
}, 
dir:function(){ 
}, 
dirxml:function(){ 
}, 
error:function(){ 
var args=Array.prototype.slice.call(arguments); 
consoleHelper.showerror(args.join(" ")); 
}, 
exception:function(){ 
}, 
group:function(name){ 
consoleHelper.showgroup(name); 
}, 
groupCollapsed:function(){ 
}, 
groupEnd:function(){ 
}, 
info:function(){ 
var args=Array.prototype.slice.call(arguments); 
if(args.length==1){ 
if(arguments[0] instanceof Array){ 
consoleHelper.showinfo("["+args[0]+"]"); 
} 
else if(arguments[0] instanceof Function){ 
consoleHelper.showinfo(args[0],"console_log_function"); 
} 
else{ 
consoleHelper.showinfo(args[0]); 
} 
} 
else{ 
consoleHelper.showinfo(args.join(" ")); 
} 
}, 
log:function(){ 
var args=Array.prototype.slice.call(arguments); 
if(args.length>1){ 
var i=1,hasstyle=false; 
if(args[0].indexOf("%c")==0){ 
args[0]=args[0].replace(/%c/,""); 
i=2; 
hasstyle=true; 
} 
for(;i<args.length;i++){ 
if(/%s|%d|%i|%o/.test(args[0])){ 
args[0]=args[0].replace(/%s|%d|%i|%o/,args[i]); 
} 
else{ 
break; 
} 
} 
if(i<args.length){ 
args[0]=args[0]+" "+args.slice(i).join(" "); 
} 
if(hasstyle){ 
consoleHelper.showlog(args[0],args[1]); 
} 
else{ 
consoleHelper.showlog(args[0]); 
} 
} 
else if(args.length==1){ 
if(arguments[0] instanceof Array){ 
consoleHelper.showlog("["+args[0]+"]"); 
} 
else if(arguments[0] instanceof Function){ 
consoleHelper.showlog(args[0],null,"console_log_function"); 
} 
else{ 
consoleHelper.showlog(args[0]); 
} 
} 
else{ 
consoleHelper.showlog(""); 
} 
}, 
memoryProfile:function(){ 
}, 
memoryProfileEnd:function(){ 
}, 
profile:function(){ 
}, 
profileEnd:function(){ 
}, 
table:function(){ 
}, 
time:function(){ 
}, 
timeEnd:function(){ 
}, 
timeStamp:function(){ 
}, 
trace:function(){ 
}, 
warn:function(){ 
var args=Array.prototype.slice.call(arguments); 
if(args.length==1){ 
if(arguments[0] instanceof Array){ 
consoleHelper.showwarn("["+args[0]+"]"); 
} 
else if(arguments[0] instanceof Function){ 
consoleHelper.showwarn(args[0],"console_log_function"); 
} 
else{ 
consoleHelper.showwarn(args[0]); 
} 
} 
else{ 
consoleHelper.showwarn(args.join(" ")); 
} 
} 
};

consoleHelper代码如下:
var consoleHelper={ 
showlog:function(val,style,cla){ 
if(cla){ 
cla="console_log "+cla; 
} 
else{ 
cla="console_log"; 
} 
this.show(val,style,cla); 
}, 
showinfo:function(val,cla){ 
if(cla){ 
cla="console_info "+cla; 
} 
else{ 
cla="console_info"; 
} 
this.show(val,null,cla); 
}, 
showwarn:function(val,cla){ 
if(cla){ 
cla="console_warn "+cla; 
} 
else{ 
cla="console_warn"; 
} 
this.show(val,null,cla); 
}, 
showerror:function(val){ 
this.show(val,null,"console_error"); 
}, 
showgroup:function(val){ 
if(!val){ 
val=""; 
} 
this.show(val+":",null,"console_group"); 
}, 
show:function(val,style,cla){ 
if(document.getElementById("showconsole")){ 
var div=document.createElement("div"); 
if(div.setAttribute){ 
if(style){ 
div.setAttribute("style",style); 
} 
} 
else{ 
if(style){ 
div=document.createElement("<div style="+style+">"); 
} 
} 
if(cla){ 
div.className=cla; 
} 
var oText=document.createTextNode(val); 
div.appendChild(oText); 
document.getElementById("showconsole").appendChild(div); 
} 
} 
};

注:如果想在页面中看到调试信息,直接在页面上添加一个id 为 showconsole 的隐藏的div即可。

样式(尽量跟FireBug保持一致):

.console_log{ 
border:1px solid #CCC; 
color:#333; 
padding:0px 5px; 
min-height:24px; 
line-height:24px; 
margin-bottom:-1px; 
} 
.console_info{ 
border:1px solid #CCC; 
color:#333; 
padding:0px 5px; 
min-height:24px; 
line-height:24px; 
margin-bottom:-1px; 
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAEEklEQVQ4jbWUW0wcZRTH/998szO7O8ByWa7WmBVKE1EpjUCt1hZsk1pCqsFL6mufauJDTQypTYHY2KbG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fF4surZyMgIOjs7+fT0tBiJRKRkMimZpimlUikbEdnI5iogu7uOBLEcAFjKWGCJpXGmh0OMMV0QBF0QhKQkSUlFUZIej0fv6OgwRV3XoaoqDMNgpmkKRLRqHIBI2v0EtPs+BvB/ts0kwABjIoAUEaWISDBNUzAMg6mqyqLR6IOl6OvrY8PDw5ibm2OhUIipqopEIsEAwG63kyzLcLvdVFpaSs3NzWhtbc2C/A18nMDdJnOGEAAAAABJRU5ErkJggg==") no-repeat scroll 0 1px #EBF5FF; 
padding-left:30px; 
} 
.console_warn{ 
border:1px solid #CCC; 
color:#333; 
padding:0px 5px; 
min-height:24px; 
line-height:24px; 
margin-bottom:-1px; 
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAD/ElEQVQ4jbWUX2gcVRSHv3tndmaTTbJJSJNWaXVNCUVjFbEWlb4U9aEYjRYURHwqKIIvgqX0oZEi+CIqCBYUjVhE8aW0xAfxSQhpSaVqETWpDdhtbWvS/NvZ2dm5c+/xIUmTdlN86oUDw71zvnvu7xx+SkS4HUvfFirg3/Lk/Lcw9tp2l9lBE8ujzrBBaWK/iT+8UI+osPMHXpxKbpWu1pNCjnZtsXH6fm2xddAWd3iqow/d3I5YgyxegpnThHpqMiiq/Xpw/DjFvv8Huy86dtTn7PF6ftem4P7nULkmCAso7YEIklQQEbLyGeT8V66wITmsd75zWPe/IbcE2+HOu+vz2UlT3LMx2PYEKNAB5LY9gy50YzPDX99/wF1dnYgFO3cR+8sRCj3J6/6+hSNrwdebZ0+/rbI4+yjV/RuD3p34YUTYHhG2RmhtlyQCrF4gbI8IWiP89iJ667Mkc7yXfdp597pgd+bDHWkU7An6dhG2V8nlI7SLwEQgdjUjq6GyCE9HhMUq4ebN2KC32Rq7f31wJnspbtX5DQpNFbI1IW4NOAZTBVNFZVVyzTFBaTs2YTD9vDdY+e36uNlUHg96N6OJwdzU4pWKRcAmS5etNAkIu1upTbVsktpsCZi4AYx4PX5b01JFN6/lPZPW0GYeFq+CqYDS0HQH2m9BtxaRuNrdCFYkykVgwkZwMg1AdWGa5sppCL3Vs2oZOh5A6wznqDdIgbMTMjvRT2cJ1HKiOMiqpJdHubLQxJW/f2Nr3uMGJxCBhQmkNmsEf6oBLKK+swvX9nragBcCArYOOLzFYdpqn9EGtBVyDQ9yaYKrmfH8yz/ONFas88eyhdq7fmtzz2o9CvDwtjxNe74bcZbs3FG0tzolApi5CGc5onseXMWtfBTevDpvU4bS6XmcFcBbjd5XYPsB7H1vce4K1/dFPGwlwszXxlTxnm/WvuIGd/P7Bj4xEyceVurffbliEZVvQSnFzO8nuFw/ibMZTRoEjZgUV52nfq1eFpd7oeXVn+1aVoMJVYaf1HJp/HCuRQ4EbdpTuTx4wdJoIeAyxCTY2JAuMm5dsLd4cObizbqva5vTF/5EDz/2kO9lB3PNPOWFtC6bGzbFmhpnTaI+nsmVvgxeOpaWSqUGhhobG2NoaMibnJz0K5VKkKZpYK0NnHM5Eck9cqdqf/5e3d/RpLpqRuo//ePOfX1WLljBKKWM1tpordMgCNJCoZCWSiVz6NAh6xtjiOOYLMuUtVaLyEp4gH+qbOunyvbX5Y4pwAK+UkoAJyJORLS1VmdZpuI4VlEUrS/FyMiIGh0dpVwuq9nZWRXHMUmSKIB8Pi9hGNLV1SU9PT2ye/duBgYGGiD/AVNZApv23zD/AAAAAElFTkSuQmCC") no-repeat scroll 0 1px #FFFFC8; 
padding-left:30px; 
} 
.console_error{ 
border:1px solid #CCC; 
color:#FF0000; 
padding:0px 5px; 
min-height:24px; 
line-height:24px; 
margin-bottom:-1px; 
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAACYQAAAmEBwTBV+gAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAQHSURBVDiNtZVtbxRVFMd/596ZnS1L210otMB2t62gmKA2gVLtC5UgaG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Zm8Naup2zbNuYuXqA8uuGx7z8zeh979x68oSHK0i7BcCVgBqrHk61cvpxfBp5o27uxoALnjEjjnOdh8gWcSBj5V/IAMo+mUZZFYHUIkGvay71edfp0qcMta5sTbW3lBUefRMneZbQn608t+fer+k6PLV18cqPftcsar15zEOEjDDtXAP5hjHTVfHfy/JM2V/yDLGj8wIF6Uf5+IyYoRpIGPymih9f3/XD1aeeeCf6v+gfLYZXwkd5f2QAAAABJRU5ErkJggg==") no-repeat scroll 0 1px #FFEBEB; 
padding-left:30px; 
} 
.console_group{ 
margin-top:20px; 
font-size:16px; 
font-weight:bolder; 
} 
.console_log_function{ 
color:green; 
}

这里为了演示方便,三个小图标直接用的是base64格式的图片,就是上面代码中的三个长字符串,大家用时可以换成图片地址。
完整代码:
JSCode 
Login 
Result 
JavaScript 
HTML 
CSS 
ALL 
Edit 
Share 
DownLoad 
<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
<title>自定义console</title> 
<style type="text/css"> 
.console_log{ 
border:1px solid #CCC; 
color:#333; 
padding:0px 5px; 
min-height:24px; 
line-height:24px; 
margin-bottom:-1px; 
} 
.console_info{ 
border:1px solid #CCC; 
color:#333; 
padding:0px 5px; 
min-height:24px; 
line-height:24px; 
margin-bottom:-1px; 
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAEEklEQVQ4jbWUW0wcZRTH/998szO7O8ByWa7WmBVKE1EpjUCt1hZsk1pCqsFL6mufauJDTQypTYHY2KbGmChp+mBsfDBtNFJDArWVWlAJsqxpKYGYsiJpKVso2y3sZXZnZ2aPDyNkl23Vl05ykvnO5Tdn/ufMMCLCo7iER0IFIP5Xgru2LS8ai9cRUQUAMMYCOYrjWvB6T/jf6tjDpHBubKkxnRVH3ZUNLU9W1+Q48koAAPHwXfw1PRUNzoz1czVwTPX3T/0v8MHD3ezL7356L++ZN05sbd5nKylQ4LAxKLIVj2pATCPc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MDdJnOGEAAAAABJRU5ErkJggg==") no-repeat scroll 0 1px #EBF5FF; 
padding-left:30px; 
} 
.console_warn{ 
border:1px solid #CCC; 
color:#333; 
padding:0px 5px; 
min-height:24px; 
line-height:24px; 
margin-bottom:-1px; 
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAD/ElEQVQ4jbWUX2gcVRSHv3tndmaTTbJJSJNWaXVNCUVjFbEWlb4U9aEYjRYURHwqKIIvgqX0oZEi+CIqCBYUjVhE8aW0xAfxSQhpSaVqETWpDdhtbWvS/NvZ2dm5c+/xIUmTdlN86oUDw71zvnvu7xx+SkS4HUvfFirg3/Lk/Lcw9tp2l9lBE8ujzrBBaWK/iT+8UI+osPMHXpxKbpWu1pNCjnZtsXH6fm2xddAWd3iqow/d3I5YgyxegpnThHpqMiiq/Xpw/DjFvv8Huy86dtTn7PF6ftem4P7nULkmCAso7YEIklQQEbLyGeT8V66wITmsd75zWPe/IbcE2+HOu+vz2UlT3LMx2PYEKNAB5LY9gy50YzPDX99/wF1dnYgFO3cR+8sRCj3J6/6+hSNrwdebZ0+/rbI4+yjV/RuD3p34YUTYHhG2RmhtlyQCrF4gbI8IWiP89iJ667Mkc7yXfdp597pgd+bDHWkU7An6dhG2V8nlI7SLwEQgdjUjq6GyCE9HhMUq4ebN2KC32Rq7f31wJnspbtX5DQpNFbI1IW4NOAZTBVNFZVVyzTFBaTs2YTD9vDdY+e36uNlUHg96N6OJwdzU4pWKRcAmS5etNAkIu1upTbVsktpsCZi4AYx4PX5b01JFN6/lPZPW0GYeFq+CqYDS0HQH2m9BtxaRuNrdCFYkykVgwkZwMg1AdWGa5sppCL3Vs2oZOh5A6wznqDdIgbMTMjvRT2cJ1HKiOMiqpJdHubLQxJW/f2Nr3uMGJxCBhQmkNmsEf6oBLKK+swvX9nragBcCArYOOLzFYdpqn9EGtBVyDQ9yaYKrmfH8yz/ONFas88eyhdq7fmtzz2o9CvDwtjxNe74bcZbs3FG0tzolApi5CGc5onseXMWtfBTevDpvU4bS6XmcFcBbjd5XYPsB7H1vce4K1/dFPGwlwszXxlTxnm/WvuIGd/P7Bj4xEyceVurffbliEZVvQSnFzO8nuFw/ibMZTRoEjZgUV52nfq1eFpd7oeXVn+1aVoMJVYaf1HJp/HCuRQ4EbdpTuTx4wdJoIeAyxCTY2JAuMm5dsLd4cObizbqva5vTF/5EDz/2kO9lB3PNPOWFtC6bGzbFmhpnTaI+nsmVvgxeOpaWSqUGhhobG2NoaMibnJz0K5VKkKZpYK0NnHM5Eck9cqdqf/5e3d/RpLpqRuo//ePOfX1WLljBKKWM1tpordMgCNJCoZCWSiVz6NAh6xtjiOOYLMuUtVaLyEp4gH+qbOunyvbX5Y4pwAK+UkoAJyJORLS1VmdZpuI4VlEUrS/FyMiIGh0dpVwuq9nZWRXHMUmSKIB8Pi9hGNLV1SU9PT2ye/duBgYGGiD/AVNZApv23zD/AAAAAElFTkSuQmCC") no-repeat scroll 0 1px #FFFFC8; 
padding-left:30px; 
} 
.console_error{ 
border:1px solid #CCC; 
color:#FF0000; 
padding:0px 5px; 
min-height:24px; 
line-height:24px; 
margin-bottom:-1px; 
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAACYQAAAmEBwTBV+gAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAQHSURBVDiNtZVtbxRVFMd/596ZnS1L210otMB2t62gmKA2gVLtC5UgaGi0Eg2JfgY+AdAWWq0fgKJGE33ZqCQF5EFqCIoJ0RoTXpRATHjY0hYa2i6d7XZ2u7tzfbHttlgKiYn/5M5N7j33N+fMOfeMGGP4P2Q9yyCxSloUxBAioCKIyviW1R9/5N152jlZyeORkOwz6A5VVdWsa2uxamOAonB/hPzoCH4yOahE922acHsxJv9M8L2QbETbp/SmaNOqtv1Yz20BgeJD5ichf+c23oWzFMbHB4I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Xwkd5f2QAAAABJRU5ErkJggg==") no-repeat scroll 0 1px #FFEBEB; 
padding-left:30px; 
} 
.console_group{ 
margin-top:20px; 
font-size:16px; 
font-weight:bolder; 
} 
.console_log_function{ 
color:green; 
} 
</style> 
<script type="text/javascript"> 
var console={ 
assert:function(){ 
}, 
clear:function(){ 
}, 
count:function(){ 
}, 
debug:function(){ 
}, 
dir:function(){ 
}, 
dirxml:function(){ 
}, 
error:function(){ 
var args=Array.prototype.slice.call(arguments); 
consoleHelper.showerror(args.join(" ")); 
}, 
exception:function(){ 
}, 
group:function(name){ 
consoleHelper.showgroup(name); 
}, 
groupCollapsed:function(){ 
}, 
groupEnd:function(){ 
}, 
info:function(){ 
var args=Array.prototype.slice.call(arguments); 
if(args.length==1){ 
if(arguments[0] instanceof Array){ 
consoleHelper.showinfo("["+args[0]+"]"); 
} 
else if(arguments[0] instanceof Function){ 
consoleHelper.showinfo(args[0],"console_log_function"); 
} 
else{ 
consoleHelper.showinfo(args[0]); 
} 
} 
else{ 
consoleHelper.showinfo(args.join(" ")); 
} 
}, 
log:function(){ 
var args=Array.prototype.slice.call(arguments); 
if(args.length>1){ 
var i=1,hasstyle=false; 
if(args[0].indexOf("%c")==0){ 
args[0]=args[0].replace(/%c/,""); 
i=2; 
hasstyle=true; 
} 
for(;i<args.length;i++){ 
if(/%s|%d|%i|%o/.test(args[0])) { 
args[0]=args[0].replace(/%s|%d|%i|%o/,args[i]); 
} 
else{ 
break; 
} 
} 
if(i<args.length){ 
args[0]=args[0]+" "+args.slice(i).join(" "); 
} 
if(hasstyle){ 
consoleHelper.showlog(args[0],args[1]); 
} 
else{ 
consoleHelper.showlog(args[0]); 
} 
} 
else if(args.length==1){ 
if(arguments[0] instanceof Array){ 
consoleHelper.showlog("["+args[0]+"]"); 
} 
else if(arguments[0] instanceof Function){ 
consoleHelper.showlog(args[0],null,"console_log_function"); 
} 
else{ 
consoleHelper.showlog(args[0]); 
} 
} 
else{ 
consoleHelper.showlog(""); 
} 
}, 
memoryProfile:function(){ 
}, 
memoryProfileEnd:function(){ 
}, 
profile:function(){ 
}, 
profileEnd:function(){ 
}, 
table:function(){ 
}, 
time:function(){ 
}, 
timeEnd:function(){ 
}, 
timeStamp:function(){ 
}, 
trace:function(){ 
}, 
warn:function(){ 
var args=Array.prototype.slice.call(arguments); 
if(args.length==1){ 
if(arguments[0] instanceof Array){ 
consoleHelper.showwarn("["+args[0]+"]"); 
} 
else if(arguments[0] instanceof Function){ 
consoleHelper.showwarn(args[0],"console_log_function"); 
} 
else{ 
consoleHelper.showwarn(args[0]); 
} 
} 
else{ 
consoleHelper.showwarn(args.join(" ")); 
} 
} 
}; 
var consoleHelper={ 
showlog:function(val,style,cla){ 
if(cla){ 
cla="console_log "+cla; 
} 
else{ 
cla="console_log"; 
} 
this.show(val,style,cla); 
}, 
showinfo:function(val,cla){ 
if(cla){ 
cla="console_info "+cla; 
} 
else{ 
cla="console_info"; 
} 
this.show(val,null,cla); 
}, 
showwarn:function(val,cla){ 
if(cla){ 
cla="console_warn "+cla; 
} 
else{ 
cla="console_warn"; 
} 
this.show(val,null,cla); 
}, 
showerror:function(val){ 
this.show(val,null,"console_error"); 
}, 
showgroup:function(val){ 
if(!val){ 
val=""; 
} 
this.show(val+":",null,"console_group"); 
}, 
show:function(val,style,cla){ 
if(document.getElementById("showconsole")){ 
var div=document.createElement("div"); 
if(div.setAttribute){ 
if(style){ 
div.setAttribute("style",style); 
} 
} 
else{ 
if(style){ 
div=document.createElement("<div style="+style+">"); 
} 
} 
if(cla){ 
div.className=cla; 
} 
var oText=document.createTextNode(val); 
div.appendChild(oText); 
document.getElementById("showconsole").appendChild(div); 
} 
} 
}; 
window.onload=function(){ 
console.group("log"); 
console.log('%c a %s This is red text on a green background','color:red; background-color:#EEE'); 
console.log("The %%s jumped over %d tall buildings",1, "abc",1); 
console.log("I am %s and I have:", "abc", "bcd","cde"); 
console.log("abc",1); 
console.log([1,2,3,4,5]); 
console.log(); 
console.log(test); 
console.group("info"); 
console.info('%c a %s This is red text on a green background','color:red; background-color:#EEE'); 
console.info("The %%s jumped over %d tall buildings",1, "abc",1); 
console.info("I am %s and I have:", "abc", "bcd","cde"); 
console.info("abc",1); 
console.info([1,2,3,4,5]); 
console.info(); 
console.info(test); 
console.group("warn"); 
console.warn('%c a %s This is red text on a green background','color:red; background-color:#EEE'); 
console.warn("The %%s jumped over %d tall buildings",1, "abc",1); 
console.warn("I am %s and I have:", "abc", "bcd","cde"); 
console.warn("abc",1); 
console.warn([1,2,3,4,5]); 
console.warn(); 
console.warn(test); 
console.group("error"); 
console.error('%c a %s This is red text on a green background','color:red; background-color:#EEE'); 
console.error("The %%s jumped over %d tall buildings",1, "abc",1); 
console.error("I am %s and I have:", "abc", "bcd","cde"); 
console.error("abc",1); 
console.error([1,2,3,4,5]); 
console.error(test); 
} 
function test(){ 
alert("abc"); 
alert("abc"); 
alert("abc"); 
alert("abc"); 
alert("abc"); 
alert("abc"); 
alert("abc"); 
alert("abc");alert("abc"); 
} 
</script> 
</head> 
<body> 
<h1>自定义console(Artwl.cnblogs.com)</h1> 
<div id="showconsole"></div> 
</body> 
</html>

小结

写这个JS一方面是工作中有这方面的需求,另外也是因为在博问中看到有人问 JavaScript中如何获得console.log的值? ,前段时间有个国外学编程网站可以把console.log的结果直接显示在页面上,不知道是不是用了本文类似的方案。

欢迎大家留言讨论。
作者:Artwl

Javascript 相关文章推荐
浅析showModalDialog数据缓存问题(用禁止浏览器缓存解决)
Jul 09 Javascript
addEventListener()第三个参数useCapture (Boolean)详细解析
Nov 07 Javascript
javascript实例分享---具有立体效果的图片特效
Jun 08 Javascript
详谈jQuery操纵DOM元素属性 attr()和removeAtrr()方法
Jan 22 Javascript
js实现每日自动换一张图片的方法
May 04 Javascript
jquery实现具有嵌套功能的选项卡
Feb 12 Javascript
JQuery ztree 异步加载实例讲解
Feb 25 Javascript
解决Node.js使用MySQL出现connect ECONNREFUSED 127.0.0.1:3306的问题
Mar 09 Javascript
浅谈node中的exports与module.exports的关系
Aug 01 Javascript
js移动端图片压缩上传功能
Aug 18 Javascript
小程序实现长按保存图片的方法
Dec 31 Javascript
JavaScript中的类型检查
Feb 03 Javascript
浏览器解析js生成的html出现样式问题的解决方法
Apr 16 #Javascript
基于jquery的不规则矩形的排列实现代码
Apr 16 #Javascript
JavaScript打开word文档的实现代码(c#)
Apr 16 #Javascript
jQuery UI Autocomplete 1.8.16 中文输入修正代码
Apr 16 #Javascript
Moment.js 不容错过的超棒Javascript日期处理类库
Apr 15 #Javascript
5个最佳的Javascript日期处理类库分享
Apr 15 #Javascript
你需要知道的10个最佳javascript开发实践小结
Apr 15 #Javascript
You might like
在PHP中利用XML技术构造远程服务(下)
2006/10/09 PHP
一个ftp类(ini.php)
2006/10/09 PHP
PHP之变量、常量学习笔记
2008/03/27 PHP
Sorting Array Values in PHP(数组排序)
2011/09/15 PHP
WordPress中编写自定义存储字段的相关PHP函数解析
2015/12/25 PHP
php 读取输出其他文件的实现方法
2016/07/26 PHP
php 无限分类 树形数据格式化代码
2016/10/11 PHP
使用Jquery来实现可以输入值的下拉选单 雏型
2011/12/06 Javascript
鼠标滚轮控制网页横向移动实现思路
2013/03/22 Javascript
利用a标签自动解析URL分析网址实例
2014/10/20 Javascript
Node.js中JavaScript操作MySQL的常用方法整理
2016/03/01 Javascript
常用原生JS兼容性写法汇总
2016/04/27 Javascript
jQuery选择器_动力节点Java学院整理
2017/07/05 jQuery
Vue resource中的GET与POST请求的实例代码
2017/07/21 Javascript
vue.js异步上传文件前后端实现代码
2017/08/22 Javascript
使用Vue开发一个实时性时间转换指令
2018/01/17 Javascript
详解vue-cli 快速搭建单页应用之遇到的问题及解决办法
2018/03/01 Javascript
[48:41]VP vs VG Supermajor小组赛 B组胜者组决赛 BO3 第二场 6.2
2018/06/03 DOTA
python遍历文件夹并删除特定格式文件的示例
2014/03/05 Python
Python设计模式之观察者模式实例
2014/04/26 Python
python实现简易内存监控
2018/06/21 Python
python pycharm的安装及其使用
2019/10/11 Python
python pymysql链接数据库查询结果转为Dataframe实例
2020/06/05 Python
Python实现Keras搭建神经网络训练分类模型教程
2020/06/12 Python
用于ETL的Python数据转换工具详解
2020/07/21 Python
Django-Scrapy生成后端json接口的方法示例
2020/10/06 Python
用html5实现语音搜索框的方法
2014/03/18 HTML / CSS
三星英国官网:Samsung英国
2018/09/25 全球购物
Pedro官网:新加坡时尚品牌
2019/08/27 全球购物
财务管理专业毕业生求职信范文
2013/09/21 职场文书
师范应届生教师求职信
2013/11/05 职场文书
教师应聘个人求职信
2013/12/10 职场文书
大学生自助营养快餐店创业计划书
2014/01/13 职场文书
海上钢琴师观后感
2015/06/03 职场文书
2016年11月份红领巾广播稿
2015/12/21 职场文书
golang json数组拼接的实例
2021/04/28 Golang