But both of these methods have its limitations, alert can be interrupted, sometimes the value of alert is not reliable, and when you close the packet alert may get incorrect values. Debugger use is actually very tangled, only IE support. So the most reasonable way is JS to run the process needs to debug the value of output to the page, or write to the cookie can also be, this way will not be alert interrupt to bring the wrong value, and will not be limited by the browser type, the only tangle is the operation is very troublesome.
So, with the following JS component. The implementation of this component refers to the recording of log4net components, we use this JS logger components, you can use log output to do your debugging work.
Copy Code code as follows:
/*
JS Debugging components
*/
(function () {
var logger = function (level, object, ViewType) {
This.level = level;
This.object = object;
This.viewtype = ViewType;
}
Logger. Level_debug = 0;
Logger. Level_info = 1;
Logger. Level_warn = 2;
Logger. Level_error = 3;
Logger. Level_fatal = 4;
Logger. View_type_alert = 0;
Logger. View_type_append = 1;
Logger.prototype = {
Setlevel:function (level) {
This.level = level;
},
Setobject:function (o) {
if (typeof o = = ' string ') {
This.object = document.getElementById (o);
} else {
This.object = O;
}
},
Setviewtype:function (type) {
This.viewtype = type;
},
Log:function (s) {
This.message (s);
},
Debug:function (s) {
This.message (logger. Level_debug, s);
},
Info:function (s) {
This.message (logger. Level_info, s);
},
Warn:function (s) {
This.message (logger. Level_warn, s);
},
Error:function (s) {
This.message (logger. Level_error, s);
},
Fatal:function (s) {
This.message (logger. Level_fatal, s);
},
Message:function (level, s) {
if (level >= this.level) {
if (this.object!= null) {
This.object.innerHTML = s;
else if (This.viewtype = logger. View_type_alert) {
alert (s);
} else {
Document.body.appendChild (document.createTextNode (s));
Document.body.appendChild (document.createelement ("BR"));
}
}
}
};
if (typeof window. Logger = = ' undefined ' | | Window. Logger = null)
Window. Logger = new Logger (Logger. Level_debug, NULL, logger. View_type_append);
})();
How to use it?
This JS component registers the Logger object with the Window object, we can use Logger.log/logger.debug/logger.info/logger.warn/logger.error/logger.fatal to output different debugging information.
The sample code is as follows:
Copy Code code as follows:
Logger.debug (New Date ());
Logger.debug (New Date (). AddHours (3));
It's easy to write Document.getelementid () innerHTML or Alert/debugger in every place.
The addhours used in the sample code is my Date object method of extending JS, and I want to know more friends to see the date method of extending JS.