javascript – 在Console.Log()中显示HTML而不是jQuery选择对象
作者:互联网
我将在Chrome开发人员控制台中输出真正的html,以便于调试.
所以我想做一个chrome扩展,即Chrome Extension.
我将真正的console.log()复制到console.nativeLog();我将自己的自定义函数添加到console.log();
这是代码:
<div class="myDiv">
<input type="text" id="inp1" title="title1" />
<input type="text" id="inp2" title="title2" />
<input type="text" id="inp3" title="title3" />
<input type="text" id="inp4" />
<input type="text" id="test" value="">
</div>
<input type="button" id="btn1" value="Add" />
<script type="text/javascript">
console.nativeLog = console.log;
var arr= new Array();
for(var i=0;i<100;i++){
arr[i] = i+','+i;
}
var fav = JSON.parse('[{"href":"/EMS-ILS/Modules/Supplier_Profile/Supplier_Profile.aspx?ModID=6&WebPageID=38","text":"Supplier Profile"},{"href":"/EMS-ILS/Modules/Customer_Profile/Customer_Profile.aspx?ModID=6&WebPageID=57","text":"Customer Profile"},{"href":"/EMS-ILS/Modules/Costing_Profile/Costing_Profile.aspx?ModID=6&WebPageID=50","text":"Costing Profile"}]')
console.log = function (val){
if(typeof(val)=='string'){
console.nativeLog(val);
return;
}
try{
for(var x=0;x<arguments.length;x++){
var arr = arguments[x];
try{
if(!arr.length)
console.nativeLog(arr);
else {
for(var i=0;i<arr.length;i++)
console.nativeLog(arr[i]);
}
}catch(err1){
console.nativeLog(arr);
}
}
}
catch(err2){
console.nativeLog(val);
}
}
$(document).ready(function(){
console.log('-------------');
console.log($('input'));
console.log('-------------');
console.log($('#inp1'));
console.log('-------------');
console.log($('#badId'));
console.log('-------------');
console.log($('input'), $('#bad'), $('input:text'), fav, 0, arr)
});
</script>
一切正常,但最后一个.如果jquery对象不包含任何结果,它仍将打印上下文jquery对象.
这是控制台中的输出.
怎么可以预防呢?有任何想法吗.谢谢.
解决方法:
看看这个小提琴http://jsfiddle.net/tppiotrowski/KYvDX/3/.这将在一个单独的行上打印每个参数,如果jQuery对象为空则打印[]:
console.nativeLog = console.log;
console.log = function(val) {
var x = 0;
for (x; x < arguments.length; x++) {
var item = arguments[x];
// check if we are dealing with jQuery object
if (item instanceof jQuery) {
// jQuery objects with length property are
// the only ones we want to print
if (item.length) {
for (var i = 0; i < item.length; i++) {
console.nativeLog(item[i]);
}
} else {
console.nativeLog('[]');
}
} else {
console.nativeLog(item);
}
}
}
这是用于打印多个参数的实际console.log行为的更准确复制,例如. console.log(‘a’,’b’,2,[])在一行:http://jsfiddle.net/tppiotrowski/KYvDX/4/
console.nativeLog = console.log;
console.log = function() {
var x = 0;
var output = [];
for (x; x < arguments.length; x++) {
item = arguments[x];
if (item instanceof jQuery) {
if (item.length) {
for (var i = 0; i < item.length; i++) {
output.push(item[i]);
}
} else {
output.push('[]');
}
} else {
output.push(item);
}
}
console.nativeLog.apply(this, output);
}
标签:jquery,javascript,google-chrome,developer-tools 来源: https://codeday.me/bug/20190709/1412343.html