2010-06-19 82 views
3

我在做我已经成功地工作一个DOM建设者,但我现在想转让的一些快捷功能,使div() - >e("div")的Javascript关闭和DOM生成器

这里是我的代码:

//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(跨度( “内容”)),跨度()):<div><div><span>Content</span></div><span></span></div>结果:<div><span></span></div>

DIV(DIV(跨度(E( “b” 的,E( “b”,E( “b”)))),跨度()))预计:<div><div><span><b><b><b></b></b></b></span><span></span></div></div>结果:<div></div>

回答

0

金发一刻,我被覆盖的第一要素,当我想用​​的是args.unshift(el);

1

尽管这并不直接回答你的问题,

for(var el in tags) { 

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

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

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

+0

哦,谢谢,我想我已经习惯了'为每个'。 – Louis 2010-06-19 14:27:19

+0

@Louis - 最近版本的JavaScript中也有'for each'。它用于枚举通过对象值,并且可以与数组一起使用,如果您不关心顺序。尝试'在Firefox中为每个({v:{a:1,b:2,c:3})console.log(v);'' – Anurag 2010-06-19 21:23:39

0

@MvanGeest - 阵列上做了for..in在技术上是允许的。数组仍然是javascript中的对象。如果循环使用for..in循环,则数组的索引将成为关键字。显然不是在这种情况下使用数组的意义,但我想我会澄清。

@Anurag - 在IE8中不支持forEach方法(不确定约9),因此可能不是一种可靠的方法,直到将来使用。