简体   繁体   English

好奇的javascript解析,甚至只返回节点。:我在这段代码中做错了什么?

[英]Curious javascript parsing, only returns even nodes.: What I'm doing wrong in this code?

I have a svg as below: 我有一个SVG如下:

<g id="proyectoActual"> 
        <g id="BORDE">
            <g id="foo"/>
        </g>

        <g id="FASES">  
            <g id="foo"/>       
        </g>

        <g id="TEXTO">  
            <g id="foo"/>
        </g>

        <g id="PROTECCIONES">
            <g id="foo"/>
        </g>

        <g id="LINEAS">
            <g id="foo"/>
        </g>

        <g id="BOLAS">
            <g id="foo"/>
        </g>
    </g>
</g>

I clone this tree with 我用这棵树克隆

var nodoClonado=gRootDibujo.cloneNode(true);

Consulting its children and its children number, it's OK. 咨询其子代及其子代号,就可以了。

When I try to add the nodes to another SVG with... 当我尝试使用...将节点添加到另一个SVG时...

for (var i=1;i<nodoClonado.childNodes.length;i++)
    contenedorBounder.appendChild (nodoClonado.childNodes[i]);

It seems only add 1, 3, 5.. (odd nodes "FASES", PROTECCIONES" and "BOLAS") . 似乎只添加1, 3, 5.. (odd nodes "FASES", PROTECCIONES" and "BOLAS")

If I change var i=2, only add 2, 4, 6 (odd nodes). 如果更改var i = 2,则仅添加2、4、6(奇数个节点)。

What have I done wrong? 我做错了什么?

Thanks in advance 提前致谢

When you append the node to some other element, the node is no longer a child of its original parent, since it has been moved to the new location in the DOM. 当您将节点附加到其他元素时,该节点不再是其原始父级的子级,因为它已被移动到DOM中的新位置。 So after you move childNodes[0] , the node that previously was in childNodes[1] moves to [0] , [2] moves to [1] , etc. When i increments to 1 , it moves childNodes[1] , which was the original [2] . 因此,在您移动childNodes[0] ,先前在childNodes[1]中的childNodes[1]将移至[0][2]移至[1]childNodes[1] 。当i增加到1 ,它将移动childNodes[1] ,这是原始的[2] So you've skipped the original [1] node. 因此,您已跳过了原始的[1]节点。 This happens for each child, so you end up copying only the original even children. 每个孩子都会发生这种情况,因此您最终只能复制原始的偶数孩子。

Instead of a for loop, you can do: 您可以执行以下操作来代替for循环:

while (nodoClonado.childNodes.length > 0) {
    contenedorBounder.appendChild (nodoClonado.childNodes[0]);
}

As Ram pointed out in his comment, you need to clone the node first. 正如Ram在其评论中指出的那样,您需要首先克隆该节点。 Just adding the node 'moves' the node to the new parent and detaches from the previous parent. 只需添加节点,即可将该节点“移动”到新的父节点,并与先前的父节点分离。

This should do the trick: 这应该可以解决问题:

for (var i=0;i<nodoClonado.childNodes.length;i++)
    contenedorBounder.appendChild (nodoClonado.childNodes[i].cloneNode(true));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM