我正在使用 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');
}
使用
输出 htmlalert($("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 解析元素时它没有任何作用。
关于javascript - for 循环内的执行顺序 - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26418940/