为什么这个 for 循环不起作用?
JavaScript:
function create(){
var newDiv = document.createElement("input");
var character = "piyush";
var i =0;
newDiv.type = "text";
newDiv.style.background = "red";
newDiv.style.width ="20px";
newDiv.style.height ="20px";
for( i =0; i< character.length ; i++)
{
document.getElementById("tryingin").appendChild(newDiv);
}
}
html:
<div id="tryingin" onMouseOut="create()" style="width:200px; height:200px; background-color:black"> </div>
现在当我在 for 循环中发出警报时。我一个接一个地看到警报框 6 次(如 character.length == 6)。但为什么我没有看到分区中附加 6 个文本框? 一次性追加所有 6 个文本框的正确代码应该是什么。
感谢帮助。 问候!
最佳答案
如果某个元素已经是 DOM 的一部分,.appendChild
将首先将其与当前父元素分离,然后将其附加到新的父元素。来自 MDN documentation :
If
child
is a reference to an existing node in the document,appendChild
moves it from its current position to the new position (i.e. there is no requirement to remove the node from its parent node before appending it to some other node).
在您的情况下,您只有一个 DOM 元素。如果你想复制该元素,可以clone it :
var parent = document.getElementById("tryingin");
for (...) {
parent.appendChild(newDiv.cloneNode());
}
关于JavaScript:for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14318416/