Javascript 闭包和 DOM 生成器

标签 javascript dom closures

我正在制作一个 DOM 生成器,我已经成功地工作了,但现在我正在尝试分配一些速记函数,以便 div() -> e("div")

这是我的代码:

//assign these objects to a namespace, defaults to window
(function(parent) {

/**
* Creates string of element
* @param tag The element to add
* @param options An object of attributes to add
* @param child ... n Child elements to nest
* @return HTML string to use with innerHTML
*/
var e = function(tag, options) {
    var html = '<'+tag;
    var children = Array.prototype.slice.apply(arguments, [(typeof options === "string") ? 1 : 2]);

    if(options && typeof options !== "string") {
        for(var option in options) {
            html += ' '+option+'="'+options[option]+'"';
        }
    }

    html += '>';
    for(var child in children) {
        html += children[child];
    }
    html += '</'+tag+'>';
    return html;
}

//array of tags as shorthand for e(<tag>) THIS PART NOT WORKING
var tags = "div span strong cite em li ul ol table th tr td input form textarea".split(" "), i=0;
for(; i < tags.length; i++) {
    (function(el) { //create closure to keep EL in scope
        parent[el] = function() {
            var args = Array.prototype.slice.call(arguments);
            console.log(args);
            args[0] = el; //make the first argument the shorthand tag
            return e.apply(e,args);
        };
    })(tags[i]);
}

//assign e to parent
parent.e = e;
})(window);

当前发生的情况是,每次我调用其中一个速记函数时,args 数组都会被修改,我假设需要发生的是某处的闭包,这样我创建的 args 数组在每次调用时都不会受到影响。这是单元测试的输出:

div( div( span("Content")), span()) 预计:<div><div><span>Content</span></div><span></span></div>结果:<div><span></span></div>

div( div( span( e("b", e("b", e("b")))), span())) 预计:<div><div><span><b><b><b></b></b></b></span><span></span></div></div>结果:<div></div>

最佳答案

虽然这不能直接回答你的问题,

for(var el in tags) {

不完全正确。 tags 是一个数组,不是一个对象,所以它的属性不能用for (... in ...) 来枚举。尝试

for(var el = 0; el < tags.length; el++) {

这会对解释器对您的代码的理解...以及正确执行您的算法产生巨大的影响。

关于Javascript 闭包和 DOM 生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3075749/

相关文章:

javascript - 使用闭包进行模块封装

javascript - 如何检查标签是否仅包含jquery中的特定字符

javascript - Onchange 文本框自动复选框

javascript - angular是否有任何方法来计划dom的度量和变异?

javascript - 添加到 DOM 时触发 Javascript 事件

Java Dom问题

ios - 什么时候在 swift 中使用闭包?

ios - 关闭 View 永远不会调用完成函数

javascript - 如何根据复杂性优化我的 JS 代码

javascript - 不在下拉列表中显示所选项目