为了账号安全,请及时绑定邮箱和手机立即绑定

div 在另一个 div 中使用 javascript 进行循环

div 在另一个 div 中使用 javascript 进行循环

桃花长相依 2024-01-11 14:09:13
我正在尝试使用 javascript 中的循环在另外 5 个 div 中创建 5 个 div。我已经制作了主 div,但所有小 div 均仅在一个主 div 中创建,并且仅创建了三个小 div。如何为一个主div制作一个小div?同样的事情必须重复5次。for(let n=0; n<5; n++){  var elm = document.createElement('div');  elm.id="comments";  document.getElementById('elm').appendChild(elm);  var sec = document.createElement('div');  sec.id = "sec";  document.getElementById('comments').appendChild(sec);}#elm{  width: 90vw;  height: 90vh;  background: blue; }#comments{  background: brown;  width: 100%;  height: 150px;  border: 2px solid yellow; }#sec{  width: 50px;  height: 50px;  background: chartreuse;  z-index: 1000;  border: 2px solid darkgreen; }<div id="elm"></div>
查看完整描述

1 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

该属性id在文档中必须是唯一的,class请改为使用。此外,您应该在每次迭代中将sec元素附加到当前创建的comments元素内:

for(let n=0; n<5; n++){

  var elm = document.createElement('div');

  elm.setAttribute('class',"comments");

  document.getElementById('elm').appendChild(elm);


  var sec = document.createElement('div');

  sec.setAttribute('class', "sec");

  elm.appendChild(sec); // append the sec element inside the current comments element

}

#elm{

  width: 90vw;

  height: 90vh;

  background: blue;

}

.comments{

  background: brown;

  width: 100%;

  height: 150px;

  border: 2px solid yellow;

}

.sec{

  width: 50px;

  height: 50px;

  background: chartreuse;

  z-index: 1000;

  border: 2px solid darkgreen;

}

<div id="elm"></div>



查看完整回答
反对 回复 2024-01-11
  • 1 回答
  • 0 关注
  • 28 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信