Javascript 将SVG元素转换为字符串

Javascript 将SVG元素转换为字符串,javascript,jquery,svg,Javascript,Jquery,Svg,在一个网页中,我将一个SVG文件加载到一个div中,如下所示: <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" heigh

在一个网页中,我将一个SVG文件加载到一个div中,如下所示:

<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" />]

然后通过一些循环,我将每个节点放入一个数组中,如下所示:

<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

您可以使用
HtmlElement
outerHTML

var arr = $.map($('svg *'), function(v){ return v.outerHTML; });

例如:

基因是正确的。为什么不使用
outerHTML
? 下面是一个普通JavaScript解决方案(即没有jQuery):


为什么不把它们放到一个字符串而不是数组中呢
var str+=newStuff
请共享创建数组的代码。您可以尝试
array.join(delimeter)