将 SVG 元素转换为字符串
Converting an SVG element to string
在网页中,我将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" />]
这里的问题是将它们存储为对象,我希望它存储为字符串,我已经在任何对象上尝试过 JSON.stringify 之类的东西,但到目前为止没有运气。我正在使用javascript和jQuery
您可以使用HtmlElement
outerHTML
:
var arr = $.map($('svg *'), function(v){ return v.outerHTML; });
示例:https://jsbin.com/qijicibime/edit?html,js,output
Gene 是对的。为什么不使用outerHTML
?这是vanilla JavaScript中的一个解决方案(即没有jQuery):
var nodesHTML = [].slice.call( document.querySelectorAll("svg *") ).map(
function( node ) { return node.outerHTML; });
相关文章:
- 如何在JavaScript中将字符串转换为函数引用
- 如何在 Javascript 中将变量的值从字符串转换为整数
- 将字符串转换为格式化日期
- IE在将字符串转换为日期时从日期中删除4小时
- node.js将字符串转换为要上传到Web服务器的文件
- 将字符串转换为JS对象
- 在js中将字符串转换为十六进制
- 试图了解如何使用parseFloat将字符串转换为数字
- 如何在html中将字符串转换为数字?以及如何将变量传递到scriptlet代码中
- 将字符串转换为GWT中的JSON对象(JSNI)
- 如何使用Razor显示模板将字符串转换为html字符串
- 将字符串转换为数组编号Javascript
- js字符串转换为具有两个值的对象
- 转换<a>使用jQuery将文本字符串转换为dom元素
- Jquery-将字符串转换为reg exp对象
- 使用JavaScript将客户端日期/时间字符串转换为JSON日期/时间串
- 将JavaScript字符串转换为整数
- moment js,将EST字符串转换为UTC
- 如何在javascript中将字符串转换为有效日期
- 通过JQuery将字符串转换为JSON