我尝试创建一个组,但它无法正常工作。它为 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/