不能用 for 循环附加孩子 [英] Cannot append child with for loop

查看:26
本文介绍了不能用 for 循环附加孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能用这个 for 循环附加很多块?

Why i cannot append numerous blocks with this for loop?

var di = document.createElement("div");
di.className = 'box';
di.style.width = '100px';
di.style.height = '100px';

for (var i = 0; i < 5; i++) {
    document.body.appendChild(di);
}

然而,这个有效:

for (var i = 0; i < 5; i++) {
    var di = 'di' + [i],
        di = document.createElement("div");
    di.className = 'box';
    di.style.width = '100px';
    di.style.height = '100px';
    document.body.appendChild(di);
}

但是为什么第一个不起作用?

But why the first one doesn't work?

推荐答案

在您的第一个示例中,始终附加相同的 dom 元素,因为它是在循环外定义的.在第二个中,您正确地为每次迭代创建了一个新元素.

In your first sample, the same dom element is appended all the time, because it is defined outside the loop. In the second one, you correctly create a new element for each iterations.

如果需要,您可以使用 cloneNode 创建现有元素的副本.第一个例子可以重写为:

If you want, you can create a copy of an exising element by using cloneNode. The first example could be re-written like:

var di = document.createElement("div");
di.className = 'box';
di.style.width = '100px';
di.style.height = '100px';

for (var i = 0; i < 5; i++) {
    document.body.appendChild(di.cloneNode());
}

这篇关于不能用 for 循环附加孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆