javascript - 使用 appendChild 在循环内部或外部声明 div 变量

标签 javascript

几年后我正在做一些 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/

相关文章:

javascript - Ember.JS 值绑定(bind)在 Action 中不起作用

javascript - 使用 AngularJS 从 REST 端点下载 XML

javascript - 如何使用 Jest 来测试使用 crypto 或 window.msCrypto 的函数

javascript - 调整 child 的大小,但 child 的高度最低 1

javascript - jquery 没有按预期计算总和

javascript - 无法第二次设置 WFS 过滤器

javascript - 如何使用 JavaScript 代码创建狗的年龄计算器 HTML 表单?

javascript - 将值传递给弹出窗口

javascript - 可以使用 Pushwoosh Remote API + Phonegap 发送基于 GeoZones 的推送

javascript - 开始向下滚动后更改菜单背景不透明度