我正在尝试动态创建以下HTML,如this fiddle
所示我正在尝试this way。当我点击Add To swiper-wrapper按钮时,有人可以告诉我为什么只添加第一个元素?
<div class="swiper-wrapper"></div>
<input type="button" id="addtoswipperwrapper" value="Add To swiper-wrapper" />
$(document).on("click", "#addtoswipperwrapper", function () {
var treemenudiv = $('<div class="TreeMenu" data-role="collapsible" data-collapsed="true" data-theme="a" data-content-theme="a"></div>');
var h3tagdata = '';
var searchResponse = ["T1", "T2", "T3"]
for (var i = 0; i < searchResponse.length; i++) {
h3tagdata += '<h3>' + searchResponse[i] + '</h3>';
}
treemenudiv.append(h3tagdata);
$('.swiper-wrapper').append(treemenudiv).trigger("create");;
});
答案 0 :(得分:1)
您需要将所有内容放在循环中。您无需增加h3tagdata
的值。其次将treemendiv
置于其中,它将生成并在循环执行时追加确切的次数。
修改强>
如果您只想将内容附加一次,那么您可以使用任何方式只执行一次代码。 Jquery .one()最好只用一次。
$("#addtoswipperwrapper").one("click", function () {
var h3tagdata = '';
var searchResponse = ["T1", "T2", "T3"];
for (var i = 0; i < searchResponse.length; i++) {
var treemenudiv = $('<div class="TreeMenu" data-role="collapsible" data-collapsed="true" data-theme="a" data-content-theme="a"></div>');
h3tagdata = '<h3>' + searchResponse[i] + '</h3>';
treemenudiv.append(h3tagdata);
$('.swiper-wrapper').append(treemenudiv).trigger("create");
}
});
<强> Working Demo JSFiddle. 强>
$(document).on("click", "#addtoswipperwrapper", function () {
var h3tagdata = '';
var searchResponse = ["T1", "T2", "T3"]
for (var i = 0; i < searchResponse.length; i++) {
var treemenudiv = $('<div class="TreeMenu" data-role="collapsible" data-collapsed="true" data-theme="a" data-content-theme="a"></div>');
h3tagdata = '<h3>' + searchResponse[i] + '</h3>';
console.log(h3tagdata);
treemenudiv.append(h3tagdata);
console.log(treemenudiv);
$('.swiper-wrapper').append(treemenudiv).trigger("create");
}
});