[英]How to get the svg in string format of a g element?
I would like to know if it is possible to get the contents in ag element of an svg element with jquery or javascript? 我想知道是否可以用jquery或javascript获取svg元素的ag元素中的内容?
<svg>
<g><path>...</path></g>
</svg>
<script>
var contents = $("div").append($("svg g").clone()).html();
</script>
This will work normally with the path or any part inside ag element but not the g element itself. 这将正常处理路径或g元素内的任何部分,但不适用于g元素本身。 Additionally for some reason if I ran this code: 另外由于某些原因,如果我运行以下代码:
<script>
var contents = $("div").append($("path").parent().clone()).html();
</script>
I can get the contents, but for the project I need to be able to match ag element (in this case a layer) and get it's content. 我可以获取内容,但是对于项目,我需要能够匹配ag元素(在本例中为图层)并获取其内容。
It seems to work but there are a couple of problems with your examples. 它似乎可行,但是您的示例存在两个问题。
First you can't use html()
on an SVG element (see answer here: Why .html() doesn't work with SVG selectors using jquery ? ) so it depends what you want to do with the g
element. 首先,您不能在SVG元素上使用html()
(请参见此处的答案: 为什么.html()不能与使用jquery的SVG选择器一起使用? ),所以这取决于您对g
元素的处理方式。
Second you're appending the g
element to the div
, but it needs to live inside an svg
element. 其次,您将g
元素附加到div
,但是它需要位于svg
元素内。 So for a page like this: 所以对于这样的页面:
<div>
<svg>
<g><path d='m10,10l10,0,0,-10,-10,0'></path></g>
</svg>
</div>
You can clone the g
element like this: 您可以像这样克隆g
元素:
g = $("svg g").clone();
$('svg').append(g);
// Move the cloned square
g.children().first().attr('d', 'm100,100l10,0,0,-10,-10,0');
So now you can do whatever you want with the variable g in that example (see the linked answer if you need to start editing the inner XML directly rather than use jQuery to modify the contents). 因此,现在您可以在该示例中使用变量g进行任何操作(如果需要直接开始编辑内部XML而不是使用jQuery修改内容,请参阅链接的答案)。
Fiddle: http://jsfiddle.net/SpaceDog/sXbE3/ 小提琴: http : //jsfiddle.net/SpaceDog/sXbE3/
To get the string you need to use XMLSerializer
as described in the linked answer above: 要获取字符串,您需要使用XMLSerializer
,如上面链接的答案中所述:
var s = new XMLSerializer();
var str = s.serializeToString(g[0]);
console.log(str);
Here I'm using g[0]
to get the DOM element of g. 在这里,我使用g[0]
获取g的DOM元素。 If you just want the contents try (g.children().first())[0]
. 如果只想要内容,请尝试(g.children().first())[0]
。 I've updated the fiddle. 我已经更新了小提琴。
However, depending on what you're going to do with the string you might not need to do that. 但是,根据您要对字符串进行的处理,可能不需要这样做。 jQuery can modify the elements directly -- it depends what you want to do. jQuery可以直接修改元素-这取决于您要执行的操作。
I'm not sure if this is what you meant on getting the contents of ag element. 我不确定这是否就是获取ag元素的内容的意思。 I've tried manipulating it using a simple script. 我尝试使用一个简单的脚本来操纵它。
$("[name=getElement]").click(function(){
$('.getThisElement').hide();
$("#test"+$(this).val()).show('fast');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.