2016-03-17 69 views
-1

在我已經加載了一個SVG文件,一個div網頁,看起來像這樣:轉換SVG元素串

<svg id="svg" width="500px" height="500px"> 
    <g id="1"> 
     <rect id="0" x="50" y="25" width="50px" height="50px" style="fill:blue;"/> 
     <rect id="2" x="110" y="125" width="50px" height="50px" style="fill:blue;"/> 
    </g> 
    <g id="2"> 
     <circle id="2" cx="150" cy="50" r="40" stroke-width="4" /> 
     <polygon id="3" points="200,10 250,190 160,210" style="stroke-width:1" /> 
    </g> 
</svg> 
一些循環,我把每一個節點到一個數組

然後,看起來是像這樣:

array[<g id="1"></g>,<rect id="0" x="50" y="25" width="50px" height="50px" style="fill:blue;"/>, <rect id="2" x="110" y="125" width="50px" height="50px" style="fill:blue;"/>, <g id="2"><circle id="2" cx="150" cy="50" r="40" stroke-width="4"/>,<polygon id="3" points="200,10 250,190 160,210" style="stroke-width:1" />] 

這裏的問題是它們存儲爲對象,我想它被存儲爲一個字符串,我已經嘗試之類的東西JSON.stringify上的任何對象,但至今沒有運氣。我使用JavaScript和jQuery

+0

爲什麼你不把它們放入一個字符串,而不是一個數組? 'var str + = newStuff' –

+1

請分享創建數組的代碼。 –

+0

您可以嘗試'Array.join(delimeter)' – Rajesh

回答

1

基因是正確的。爲什麼不使用outerHTML? 這裏是香草的JavaScript的解決方案(沒有jQuery的即):

var nodesHTML = [].slice.call(document.querySelectorAll("svg *")).map(
    function(node) { return node.outerHTML; });