2014-10-28 25 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