2014-10-28 26 views
0

我尝试插入SVG中的元素以在SVG DOM中添加一个图层。 SVG嵌入在HTML5中。在SVG中插入a <g>标记通过jquery

当我这样做时,移动的元素从HTML中消失。怎么了?

要在现场观看,看看这里:http://bl.ocks.org/daohodac/raw/6db306dcb5d66d913f5c/并单击按钮执行脚本

这里是多边形可见初始SVG:

<svg ...attributes...> 
    <g id="zoom_anim" ...attributes...> 
    <polygon ...attributes...></polygon> 
    </g> 
</svg> 

这里是我后脚本(我可以看到它在Chrome检查)与多边形无形

<svg ...attributes...> 
    <g id="zoom_anim_parent_bbsmashed"> 
    <g id="zoom_anim" ...attributes...> 
     <polygon ...attributes...></polygon> 
    </g> 

</svg> 

这里是脚本

<script> 
var intercalate = function() { 
    var zoomParentId = "zoom_anim_parent_bbsmashed"; 
    var gId = "#zoom_anim"; 
    $(gId).parent().append($("<g id='"+zoomParentId+"'>")); 
    var that = $(gId).detach().appendTo("#"+zoomParentId); 
}; 
</script> 

回答

1

小心使用jQuery和SVG。 SVG节点与XHTML节点不同,并且某些jQuery API无法正确使用SVG。要创建SVG节点,您应该使用document.createElementNS('http://www.w3.org/2000/svg', 'g')。你也可以使用一个SVG库,如d3snap;都提供了一个全面的API来处理SVG节点。

+0

谢谢,它用$(document.createElementNS('http://www.w3.org/2000/svg','g'))取代$(“”)很有效。 – 2014-10-29 08:17:57