gpt4 book ai didi

javascript - 如何在 Javascript 中的 for 循环内 append html 模板?

转载 作者:行者123 更新时间:2023-11-28 19:40:44 25 4
gpt4 key购买 nike

我正在尝试动态创建 100 个 li,并在每个 li 中 append 一个 html"template"。最重要的是,我想在该模板内动态地将 id="Increment"span 元素增加 1,例如... 1, 2, 3 ---> 100

期望效果:http://jsfiddle.net/LQp5y/
当前工作:http://jsfiddle.net/QyWS7/


HTML 标记:

    <section class="main">
<div class="wrapper">
<ul id="currentStore" class="row">

<!-- HTML TEMPLATE -->

</ul>

</div>
</section>



HTML 模板:

    <!-- 100 li's -->
<li>
<div class="flip-container" ontouchstart="this.classList.toggle('hover');">
<div class="flipper">
<div class="front">
<span>1</span>
</div>
<div class="back">
<span>Buy</span>
</div>
</div>
</div>
</li>


Javascript(当前)

    var toAdd = document.createDocumentFragment();
for(var i=1; i < 101; i++){
var newLi = document.createElement('li');
newLi.id = 'Product'+i;
newLi.className = 'item';
newLi.innerHTML = 'Product '+i;
toAdd.appendChild(newLi);
}

document.getElementById('currentStore').appendChild(toAdd);


有人可以告诉我正确的方法吗?提前致谢!

最佳答案

var toAdd = document.createDocumentFragment();
var i=1;
while(i < 101){
var newLi = document.createElement('li');
newLi.id = 'Product'+i;
newLi.className = 'item';
newLi.innerHTML = '<li>
<div class="flip-container" ontouchstart="this.classList.toggle(\'hover\');">
<div class="flipper">
<div class="front">
<span>'+i+'</span>
</div>
<div class="back">
<span>Buy</span>
</div>
</div>
</div>
</li>';
toAdd.appendChild(newLi);
i++;
}

document.getElementById('currentStore').appendChild(toAdd);

关于javascript - 如何在 Javascript 中的 for 循环内 append html 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25092849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com