簡體   English   中英

for循環內的執行順序-jQuery

[英]Execution order inside for loop - jQuery

我正在使用for循環生成一個動態div,我對輸出感到驚訝。 該代碼如下所示:

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');
}

輸出的HTML使用

alert($("div#Display").clone().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> ,但是我希望它們在html的末尾,因為我在for循環中最后調用了它們。 循環是否有這種行為?

當您使用jQuery解析標簽時,它會創建一個DOM對象,其中也包含關閉標簽。 如果您想讓$('<div class="col-md-4"><div class="thumbnail">...進入$('<div id="'+continent+'Display"><div class="row top-buffer">')您需要將其附加到'#' + continent + '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>').appendTo('#Display'); ,使用jQuery解析元素時沒有任何作用。

代碼$('<div id="Display"><div class="row top-buffer">')將創建jquery對象,因此,如果追加它,則html看起來像這樣

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

如果要在末尾附加</div></div> ,則將所有html保存在變量中,並在末尾附加

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM