我尝试创建一个组,但是它不能正常工作。它为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>
答案 0 :(得分:1)
如果DOM中已经存在该元素,则appendChild会将其移动到另一个位置。要获得2个元素,您应该创建2个节点并将其附加。您还可以附加节点的副本:
document.getElementById('g').appendChild(e.cloneNode(true));
来自MDN:
如果给定子级是对文档中现有节点的引用,则appendChild()将其从其当前位置移至新位置(在将其附加到其他节点之前,无需从其父节点中删除该节点节点)。
答案 1 :(得分:1)
在不克隆同一元素的情况下,您不能两次附加该元素,一种快速的解决方案是在循环内创建一个新元素。
for (i=0; i<10; i++){
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('group').appendChild(g);
}
alert(g.children.length); // returns 10
<html>
<body>
<svg id="test" width="100%" height="100%">
<svg id="group">
<g id="g"></g>
</svg>
</svg>
</body>
</html>