나는 성공적으로 작업을 가지고 DOM 빌더를 만드는 중이라서하지만 지금은 좀 속기 기능을 할당하려고 그래서 div()
-> 다음자바 스크립트 폐쇄 및 DOM Builder는
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 (스팬 ("콘텐츠")), 스팬()) : <div><div><span>Content</span></div><span></span></div>
결과 : <div><span></span></div>
DIV (DIV (스팬 (E ("B"다음은 단위 테스트의 출력은 전자 ("B", 전자 ("B")))), 스팬())) 예상 : <div><div><span><b><b><b></b></b></b></span><span></span></div></div>
결과 :이 비록 <div></div>
오, 고마워, 나는 '각각을 위해'익숙해 졌어. – Louis
@ 루이스 - 최근 버전의 자바 스크립트에는 '각 사용자 용'도 있습니다. 객체 값을 통해 열거하는 데 사용되며 주문에 신경 쓰지 않으면 배열과 함께 사용할 수 있습니다. Firefox에서는 {(a : 1, b : 2, c : 3}) console.log (v); 각각에 대해'를 시도해보십시오. – Anurag