4 回答
TA贡献1815条经验 获得超13个赞
您可以使用innerHTML
numCards = 16;
let html = "";
for (var i = 0; i < numCards; i++)
{
html += '<div id="image' + i + '"><img src="images/desiredImage.png"></div>'
}
document.getElementById("parent").innerHTML = html;
<div id="parent">
<div>
TA贡献1872条经验 获得超3个赞
让 jQuery 来完成工作,而不是定义卡片的长度(这实际上取决于您)。这是我的解决方案。
var card_parent = jQuery(document).find('div.card_parent');
var numCards = card_parent.children('div.numCards').length;
console.log( numCards + ': total cards'); //this is your number of cards in page
jQuery('div.numCards').each(function( card_count )
{
console.log( 'card ' + card_count + ' id => ' + jQuery(this).attr('id') );
card_count++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card_parent"><!-- add a parent that nest the number of cards -->
<div id="card_1" class="numCards">card 1</div><!--for each class uses a singular class -->
<div id="card_2" class="numCards">card 2</div>
<div id="card_3" class="numCards">card 3</div>
<div id="card_4" class="numCards">card 4</div>
<div id="card_5" class="numCards">card 5</div>
<div id="card_6" class="numCards">card 6</div>
<div id="card_7" class="numCards">card 7</div>
<div id="card_8" class="numCards">card 8</div>
<div id="card_9" class="numCards">card 9</div>
<div id="card_10" class="numCards">card 10</div>
<div id="card_11" class="numCards">card 11</div>
<div id="card_12" class="numCards">card 12</div>
<div id="card_13" class="numCards">card 13</div>
<div id="card_14" class="numCards">card 14</div>
<div id="card_15" class="numCards">card 15</div>
<div id="it_works" class="numCards">card 16</div>
</div>
TA贡献1824条经验 获得超6个赞
numCards = 16;
const parent = document.querySelector("#parent")
for (var i = 0; i < numCards; i++)
{
html += `<div id="image${i}"><img src="images/desiredImage.png"></div>`
parent.insertAdjacentHTML("afterbegin",html)
}
请注意,我使用反引号 `` 和带美元符号的大括号
反引号代替引号
美元符号意味着您想在此处附加一些随机或特殊内容
大括号是特殊内容的容器
TA贡献1818条经验 获得超3个赞
您正在寻找node.appendChild(myDiv);
( appendChild() )
所以对于这个循环我建议:
const numCards = 16;
const parent = document.getElementById('parentDiv');
for (var i = 0; i < numCards; i++)
{
// using template literals is cleaner
const div = `<div id="image${i}"><img src="images/desiredImage.png"></div>`
// append the new div to the parent
parent.appendChild(div);
}
添加回答
举报