[英]Create SVG group with JavaScript returns false children.length
我嘗試創建一個組,但無法正常工作。 它為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 :
如果給定的子對象是對文檔中現有節點的引用,則appendChild()將其從其當前位置移動到新位置(在將其附加到其他節點之前,不需要從其父節點中刪除該節點)。
您不能兩次克隆相同的元素而不將其克隆,一種快速的解決方案是在循環內創建一個新元素。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.