为什么我的div不会像循环那样多次打印? 我希望图片显示10次,出于某种原因只显示两次。任何想法,所有帮助都欢迎和赞赏。谢谢!
我选择Div,我克隆它,现在我想要显示它10次。
var stuffIWantRepeated = document.getElementsByTagName("DIV")[0];
var clone = stuffIWantRepeated.cloneNode(true);
for (var i = 1; i <= 10; i++) {
document.body.appendChild(clone);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#maindiv img {
border-bottom-color: black;
display: block;
margin-left: auto;
margin-right: auto;
}
#maindiv {
padding-top: 10%;
}
</style>
</head>
<body>
<div id="maindiv">
<img src="https://pbs.twimg.com/profile_images/571024672750178304/GpGC8aTW.jpeg" border="40">
</div>
</body>
</html>
答案 0 :(得分:1)
每次要追加时都必须克隆一次。特定节点只能在一个地方的DOM中。
将该行移动到循环中:
for(var i = 1; i <= 10; i++) {
var clone = stuffIWantRepeated.cloneNode(true);
document.body.appendChild(clone);
}
答案 1 :(得分:0)
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#maindiv img {
border-bottom-color: black;
display: block;
margin-left: auto;
margin-right: auto;
}
#maindiv {
padding-top: 10%;
}
</style>
</head>
<body>
<div id="maindiv">
<img src="https://pbs.twimg.com/profile_images/571024672750178304/GpGC8aTW.jpeg" border="40">
</div>
</body>
<script>
var stuffIWantRepeated = document.getElementsByTagName("DIV")[0];
for (var i = 1; i <= 10; i++) {
var clone = stuffIWantRepeated.cloneNode(true);
document.body.appendChild(clone);
}
</script>
</html>
&#13;
答案 2 :(得分:0)
不是创建一个克隆并将其附加十次,而是应该创建十个克隆并单独追加每个克隆:
替换:
<script>
var stuffIWantRepeated = document.getElementsByTagName("DIV")[0];
var clone = stuffIWantRepeated.cloneNode(true);
for(var i = 1; i <= 10; i++) {
document.body.appendChild(clone);
}
</script>
有了这个:
<script>
var stuffIWantRepeated = document.getElementsByTagName("DIV")[0];
for(var i = 1; i <= 10; i++) {
var clone = stuffIWantRepeated.cloneNode(true);
document.body.appendChild(clone);
}
</script>
答案 3 :(得分:0)
每次循环都需要克隆它。一旦附加到文档中,克隆就会失效。
var stuffIWantRepeated = document.querySelectorAll("DIV")[0];
for (var i = 1; i <= 10; i++) {
var clone = stuffIWantRepeated.cloneNode(true);
document.body.appendChild(clone);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#maindiv img {
border-bottom-color: black;
display: block;
margin-left: auto;
margin-right: auto;
}
#maindiv {
padding-top: 10%;
}
</style>
</head>
<body>
<div id="maindiv">
<img src="https://pbs.twimg.com/profile_images/571024672750178304/GpGC8aTW.jpeg" border="40">
</div>
</body>
</html>