几年后我正在做一些 JavaScript 练习,但没有使用它,所以如果这是一个愚蠢的问题,我深表歉意。
我从一个简单的循环开始,输出“Hello, world!”几次:
for (i = 0; i < 5; i ++){
var div = document.createElement("div");
div.innerHTML = "Hello, world!";
document.body.appendChild(div);
}
这给了我五行“Hello, world!”。我想看看如果将变量声明移出循环,代码是否会运行得更快:
var div = document.createElement("div");
div.innerHTML = "Hello, world!";
for (i = 0; i < 5; i ++){
document.body.appendChild(div);
}
我预计会收到五行“Hello, world!”但我只有一个。谁能解释一下为什么?
谢谢!
最佳答案
在第一个片段中,您在每次迭代中创建一个新元素并将其附加。
在第二个片段中,您创建了一个单个元素,然后基本上将它移动了五次。
根据 MDN :
The
Node.appendChild()
method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document,appendChild()
moves it from its current position to the new position. This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position.
因此,您应该在使用 .cloneNode()
method 附加元素之前克隆该元素。 :
var div = document.createElement("div");
div.innerHTML = "Hello, world!";
for (i = 0; i < 5; i ++){
document.body.appendChild(div.cloneNode(true));
}
关于javascript - 使用 appendChild 在循环内部或外部声明 div 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34160222/