javascript - 使用 JavaScript 创建 SVG 组返回 falsechildren.length

标签 javascript svg

我尝试创建一个组,但它无法正常工作。它为 group.length 返回 1。我做错了什么?

<html>
<body>
  <svg id="test" width="100%" height="100%">
    <svg id="group">
      <g id="g"></g>
    </svg>
  </svg>
  <script>
    var e = document.createElementNS("http://www.w3.org/2000/svg", 'ellipse'); 
    e.setAttribute('cx', 0);
    e.setAttribute('cy', 0);
    e.setAttribute('rx', 20);
    e.setAttribute('ry', 20);
    document.getElementById('g').appendChild(e);
    document.getElementById('g').appendChild(e);
    document.getElementById('group').appendChild(g);
    alert(g.children.length); // returns 1 though I add it two times
  </script>
</body>
</html>

最佳答案

如果元素已经存在于 DOM 中,appendChild 只是将其移动到另一个位置。要获取 2 个元素,您应该创建 2 个节点并将其附加。您还可以附加节点的副本:

document.getElementById('g').appendChild(e.cloneNode(true));

来自MDN :

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 (there is no requirement to remove the node from its parent node before appending it to some other node).

关于javascript - 使用 JavaScript 创建 SVG 组返回 falsechildren.length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54847633/

相关文章:

来自数组的 Javascript 函数

javascript - D3 可折叠树路径标签颠倒

css - translate3d(0,0,0) 时不显示 SVG 图像;规则被应用。预期的?

javascript - SVG SMIL animateMotion 只触发一次

html - 如何测试 javascript 代码的速度 - SVG 与 CANVAS

javascript - 如何在bxslider中制作变体显示幻灯片?

javascript - 使用javascript,如何选择相对于特定其他li的li

javascript - 在 Accordion 中设置事件部分

javascript - ASP.NET 中 <div> 标签之间允许的最大值

javascript - 循环遍历 json 对象时,键没有添加到它