2010-06-19 85 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),因此可能不是一種可靠的方法,直到將來使用。