【发布时间】:2020-05-24 05:02:38
【问题描述】:
尝试循环遍历 DOM 中的 div 并动态渲染 300 次。在样式化元素中访问 HTML 时遇到问题。 代码如下:
JavaScript 文件:
var amount = 5;
for(var i = 0; i < amount; i++){
var new_div = document.createElement("div");
new_div.className = "hello";
document.body.appendChild(new_div).innerHTML;
console.log("This is repeat " + i)
}
HTML 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="hello">
<p>
Hello World!
</p>
</div>
<script src="app.js"></script>
</body>
</html>
CSS 样式表:
.hello {
width: 80%;
margin: 0 auto;
padding: 20px;
text-align: center;
border-style: outset;
border-width: 5px;
border-color: #d36135;
}
我希望能够多次渲染第一个 div,因为它的样式完全一致。
【问题讨论】:
标签: javascript html loops for-loop dom