我正在尝试使用JS动态创建以下html,但无法使循环工作。
我将从用户输入中收到计数值(即:1,2,3等)。
<div class='outer-1'>
<div class='inner-1'></div>
</div>
<div class='outer-2'>
<div class='inner-1'></div>
<div class='inner-2'></div>
</div>
<div class='outer-3'>
<div class='inner-1'></div>
<div class='inner-2'></div>
<div class='inner-3'></div>
</div>
........
这是我到目前为止:
var html = '';
for (var i = 1; i <= count; i++) {
html += "<div class='outer-"+ i +"'>";
html += "<div class='inner"-"+ i +"'></div>";
html += "</div>";
}
该代码仅打印如下。
<div class='outer-1'>
<div class='inner-1'></div>
</div>
<div class='outer-2'>
<div class='inner-2'></div>
</div>
答案 0 :(得分:4)
您需要一个内部循环来生成每个外部<div>
的内容。
var html = '';
for (var i = 1; i <= count; i++) {
html += "<div class='outer-"+ i + "'>";
for (var j = 1; j <= i; j++) {
html += "<div class='inner-" + j + "'></div>";
}
html += "</div>";
}
答案 1 :(得分:3)
for
循环中需要for
循环:
var html = '';
for (var i = 1; i <= count; i++) {
html += "<div class='outer-"+ i +"'>";
for (var j = 1; j <= i; j++)
html += "<div class='inner-"+ j +"'></div>";
html += "</div>";
}
答案 2 :(得分:0)
您需要使用外循环和内循环:
var html = '';
for (var i = 1; i <= count; i++) {
html += "<div class='outer-"+ i +"'>";
for (var j = 1; j <= i; j++) {
html += "<div class='inner"-"+ j +"'></div>";
}
html += "</div>";
}
答案 3 :(得分:0)
你需要一个像这样的内部div的新循环:
var count=3;
var html = '';
for (var i = 1; i <= count; i++)
{
html += "<div class='outer-"+ i +"'>" + "\n";
var inHtml = '';
for (var j = 1; j <= i; j++)
{
inHtml += "<div class='inner-"+ j +"'></div>" + "\n";
}
html += inHtml;
html += "</div>" + "\n";
}