在for循环内部时appendChild不能正常工作 [英] appendChild while inside for loop doesn't work right

查看:66
本文介绍了在for循环内部时appendChild不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个DIV,并使用for循环将其附加到页面上所有现有的DIV中.问题是当它位于for循环中时,它将仅将新的DIV添加到最后找到的DIV,而不是像FOR循环那样将其添加到每个DIV.有人可以告诉我我在做什么错吗?

I'm trying to create a DIV and append it to all existing DIVs on the page with a for loop. The problem is while it's inside the for loop, it will add the new DIV only to the last found DIV and not to each one like the FOR loop is supposed to make it do. Can anybody tell me what I'm doing wrong?

这是我正在使用的代码:

Here's the code I'm working with:

HTML:

<div class="Id">
<div class="first">First</div>
</div>

<div class="Id">
<div class="first">First</div>
</div>

<div class="Id">
<div class="first">First</div>
</div>

<div class="Id">
<div class="first">First</div>
</div>

JS:

var secondDiv, secondDivImg, selectDivContainer;

secondDivImg = document.createElement("span");
secondDivImg.className = "divImg";

secondDiv = document.createElement("div");
secondDiv.className = 'second';
secondDiv.innerHTML = "Second";
secondDiv.appendChild(secondDivImg);

selectDivContainer  = document.querySelectorAll('.Id');

var idLength = document.querySelectorAll('.Id').length;

for (var i=0; i<idLength; i++) {

    selectDivContainer[i].appendChild(secondDiv);
    console.log(i);
    console.log(selectDivContainer[i]);

}

这是小提琴

我添加了两个console.log来查看,它们看起来像是正确的东西,所以我有点困惑为什么会这样.谢谢!

I added a couple of console.log to see and they look like the right thing so I'm a little confused why this happens. Thanks!

推荐答案

您将不得不创建多个元素,因为您不能将同一元素两次附加到一个文档中.这意味着您的 document.createElement()调用必须在循环内.

You'll have to create multiple elements, since you can't append the same element to one document twice. That means your document.createElement() call must be inside the loop.

var selectDivContainer = document.querySelectorAll('.Id');
var idLength = selectDivContainer.length;

var secondDiv, secondDivImg;

for (var i = 0; i < idLength; i++) {
    secondDivImg = document.createElement("span");
    secondDivImg.className = "divImg";

    secondDiv = document.createElement("div");
    secondDiv.className = "second";
    secondDiv.innerHTML = "Second";
    secondDiv.appendChild(secondDivImg);

    selectDivContainer[i].appendChild(secondDiv);
}

此外,您可能已经注意到,我更改了代码的某些部分.例如,您应该保持一致的报价;除非必要,否则不要使用"'(在JS中也是如此).此外,对于 idLength ,您不必调用再次 document.querySelectorAll().

Also, you may have noticed that I changed some parts of your code; for example, you should be consistent in quoting; do not use " AND ' unless necessary (they are the same in JS). Also, for idLength, your don't have to call document.querySelectorAll() again.

这篇关于在for循环内部时appendChild不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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