2013-06-23 5 views
5

사용자의 Facebook 친구 목록 (JSON 객체로 가져옴)을 사용하여 select 요소를 만들고 싶습니다. 내 HTML에 <select id="friends"></select>를 하드, 다음 JSON을 구문 분석하기 위해 다음과 같은 자바 스크립트 코드를 사용하고 select 요소의 option 각 친구를 삽입 :Javascript - 여러 HTML 요소를 효율적으로 삽입하십시오.

var msgContainer = document.createDocumentFragment(); 
for (var i = 0; i < response.data.length; i++) { 
    msgContainer.appendChild(document.createTextNode('<option value="'+response.data[i].id+'">'+response.data[i].name+'</option>'));  
} 
document.getElementById("friends").appendChild(msgContainer); 

거의가 &lt;&gt; 대신 < 삽입하는 것을 제외하고 작동이 및 >. 어떻게 해결할 수 있으며, 순수한 Javascript (JQuery가 아님)를 사용하여 여러 HTML 요소를 삽입하는보다 효율적인 방법이 있습니까?

답변

19

왜 텍스트 노드를 만들지는 모르겠지만 option 요소를 만들고 싶다면 Option 생성자를 대신 사용할 수 있습니다.

var msgContainer = document.createDocumentFragment(); 

for (var i = 0; i < response.data.length; i++) { 
    msgContainer.appendChild(new Option(response.data[i].name, response.data[i].id)); 
} 
document.getElementById("friends").appendChild(msgContainer); 

아니면 일반적인 document.createElement()를 사용할 수 있습니다.

var msgContainer = document.createDocumentFragment(); 

for (var i = 0; i < response.data.length; i++) { 
    var option = msgContainer.appendChild(document.createElement("option")); 
    option.text = response.data[i].name; 
    option.value = response.data[i].id; 
} 
document.getElementById("friends").appendChild(msgContainer); 

이 요소를 생성하고 동시에 속성을 설정하기위한 도우미 기능이 좋네요.

여기에 하나의 간단한 예 : 몇 가지 구체적인 요구를 충당하기 위해 확장 할 수 있습니다

function create(name, props) { 
    var el = document.createElement(name); 
    for (var p in props) 
     el[p] = props[p]; 
    return el; 
} 

, 그러나 이것은 대부분의 경우에 작동합니다.

이처럼 사용하십시오 :

var msgContainer = document.createDocumentFragment(); 

for (var i = 0; i < response.data.length; i++) { 
    msgContainer.appendChild(create("option", { 
     text: response.data[i].name, 
     value: response.data[i].id 
    })); 
} 
document.getElementById("friends").appendChild(msgContainer); 
+0

감사합니다! 한 가지 방법이 더 효율적입니까? –

+0

@ 1 '': 여기에 두 번째 생각을하지 않겠습니다. 개인적으로 모든 요소를 ​​만들고 동시에 여러 속성을 설정할 수있는 요소 작성자 도우미 함수를 만들 것입니다. –

+1

두 번째 변형은 비효율적이고 꽤 나쁜 습관 (루프에 요소를 추가 함)이므로 첫 번째 변형이 선호됩니다. – dfsq

0

대신 루프에 대한 당신이 시도 :

var o = document.createEleent('option'); 
o.setAttribute('value', response.data[i].id); 
o.appendChild(document.createTextNode(response.data[i].name)); 
msgContainer.appendChild(o);