2014-10-17 3 views
0

for 루프를 사용하여 동적 div를 생성 중이며 출력에 놀랐습니다.for 루프 내 실행 순서 - jQuery

for(continent in CityList) 
{ 
    $('<div id="'+continent+'Display"><div class="row top-buffer">').appendTo('#Display'); 

     currentcontinent = CityList[continent]; 

    for(city in currentcontinent) { 

    $('<div class="col-md-4"><div class="thumbnail"><div class="caption"><h3>'+CityList[continent][city]['EngName']+'</h3><a data-name="'+city+'" href="#'+city+'"> <img src="'+CityList[continent][city]['src']+'" style="min-height:250px;height:250px;"/></a></div></div></div>').appendTo('#Display'); 
    } 

    $('</div></div>').appendTo('#Display'); 
} 

alert($("div#Display").clone().html()); 

를 사용하여 출력 HTML은 다음과 같습니다 : 코드는 다음과 같습니다

<div id="AmericaDisplay"><div class="row top-buffer"></div></div><div class="col-md-4"><div  class="thumbnail"><div class="caption"><h3>Boston</h3><a data-name="Boston" href="#Boston"> <img src="undefined" style="min-height:250px;height:250px;"></a></div></div></div>... 

당신은 </div></div> 첫 번째 APPEND 후,하지만 그 예상이있다 볼 수 있듯이 내가 for 루프에서 마지막으로 호출 한 이후로 html의 끝 부분에 있어야한다. 루프가 이런 식으로 행동해야하는 이유가 있습니까?

답변

1

코드 $('<div id="Display"><div class="row top-buffer">') JQuery와 객체를 생성합니다 결국 그것은

for(continent in CityList){ 
    var data = '<div id="'+continent+'Display"><div class="row top-buffer">'; 
    currentcontinent = CityList[continent]; 
    for(city in currentcontinent) { 
     data += '<div class="col-md-4"><div class="thumbnail"><div class="caption"><h3>'+CityList[continent][city]['EngName']+'</h3><a data-name="'+city+'" href="#'+city+'"> <img src="'+CityList[continent][city]['src']+'" style="min-height:250px;height:250px;"/></a></div></div></div>' 
    } 

    data += '</div></div>'; 
    $(data).appendTo('#Display'); // or ('#Display').append(data); 
} 
+1

'data' 변수의'var' 키워드를 생략함으로써 실수로 글로벌 변수의 사용을 권장합니다. 이런 전역적인 'data' 변수를 생성하고 싶지는 않습니다. 당신이 적어도 그것을 기대할 때 그것은 부랑아에 당신을 물 것입니다. – GregL

+0

고맙습니다. 해결되었습니다. –

2

태그를 jQuery와 구문 분석하면 닫는 태그도 포함 된 DOM 객체가 만들어집니다. 당신이 $('<div class="col-md-4"><div class="thumbnail">...$('<div id="'+continent+'Display"><div class="row top-buffer">') 내부에 가고 싶은 경우에 당신은과 같이 '#' + continent + 'Display'에 추가해야합니다 jQuery로 요소를 구문 분석 할 때

또한, $('</div></div>').appendTo('#Display'); 제거
$('<div class="col-md-4"><div class="thumbnail"><div class="caption"><h3>'+CityList[continent][city]['EngName']+'</h3><a data-name="'+city+'" href="#'+city+'"> <img src="'+CityList[continent][city]['src']+'" style="min-height:250px;height:250px;"/></a></div></div></div>').appendTo('#' + continent + 'Display'); 

, 그것은 어떤 목적을 제공하지 않습니다. 당신이 그것을 추가 할 경우 다음 결국 </div></div>를 추가 변수에 모든 HTML을 저장하고 추가 할 경우 HTML이

<div id="Display"> 
    <div class="row top-buffer"> 
    </div> 
</div> 

같이 있도록

+1

더 설명하기 : 호세는'.innerHTML + = ...'를 대체''.appendTo()를 사용하려고, 그것은 실제로에 전체 자식 노드를 추가하는 반면 선택된 노드. – GregL

+0

답장을 보내 주셔서 감사합니다. 현재 진행중인 작업에 대해 더 잘 이해하고 있습니다. –