重新定义变量

Redefining variable

本文关键字:变量 定义 新定义      更新时间:2023-09-26

你好,我有代码取代document.write,使缓冲区,然后将缓冲区推入文档:

var lazyLoad = (function () {
    var CONFIG = {
        block: '',
        url: ''
    };
    function work(){
        buffer = ''
        d.write = d.writeln = function(s){ 
                                    buffer += s
                                }
        d.open = d.close = function(){}
        s = d.createElement('script');       
        s.setAttribute('type','text/javascript');
        s.setAttribute('src',CONFIG.url);
        d.getElementById(CONFIG.block).appendChild(s)
        s.onload = function () {
            window.setTimeout(function() {
                console.warn(CONFIG.block + ' ' + buffer)
                d.getElementById(CONFIG.block).innerHTML += buffer;
                buffer = '';
            }, 0);
       }
    }
    return {
            init: function (options) {
                $.extend(CONFIG, options);
                window.d = document
                window.onload = function(){
                    work()
                }
            }
    }
})();

如果我初始化它一次:

lazyLoad.init({
            url: 'http://test1.com/test1.js',
            block: DIVID1
        })

但是如果我用其他参数再次调用它:

lazyLoad.init({
                url: 'http://test2.com/test2.js',
                block: DIVID2
            })

第一个init不能工作。buffer是空的。我错在哪里?

通过调用$.extend(CONFIG, options),您将用新的配置替换以前的配置。

相反,您应该创建一个数组并将每个options附加到其中。