我在做我已经成功地工作一个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>
哦,谢谢,我想我已经习惯了'为每个'。 – Louis 2010-06-19 14:27:19
@Louis - 最近版本的JavaScript中也有'for each'。它用于枚举通过对象值,并且可以与数组一起使用,如果您不关心顺序。尝试'在Firefox中为每个({v:{a:1,b:2,c:3})console.log(v);'' – Anurag 2010-06-19 21:23:39