Home > Web Front-end > JS Tutorial > body text

浏览器兼容console对象的简要解决方案分享_javascript技巧

WBOY
Release: 2016-05-16 17:19:00
Original
1077 people have browsed it

浏览器报找不到console对象,那我们就手动构造一个接口完全一致的console对象 置于window中。这里采用了空方法和空对象。如此一来即使在很old的浏览器中,含有console.xxxxx的代码依然不会报错,完美运行。

下面附上修复兼容代码,要置于置于第一句console.xxxx调用之前,否则没有意义。

复制代码 代码如下:

(function (){ 

//创建空console对象,避免JS报错 

if(!window.console) 
    window.console = {}; 
var console = window.console; 

var funcs = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 
             'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 
             'info', 'log', 'markTimeline', 'profile', 'profileEnd', 
             'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn']; 
for(var i=0,l=funcs.length;i    var func = funcs[i]; 
    if(!console[func]) 
        console[func] = function(){}; 

if(!console.memory) 
    console.memory = {}; 

})();
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!