如何使用 jQuery 或 JavaScript 从 html 页面获取 SVG 代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9871974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How get SVG code from html page, using jQuery or JavaScript?
提问by VasyambaTula
I have simple HTML page with svg like this:
我有一个带有 svg 的简单 HTML 页面,如下所示:
<div id="plan">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g id="layer3">
<rect width="105.71429" height="80" x="351.42856" y="152.36218" id="rect1" style="fill:#008000"></rect>
<rect width="120" height="85.714287" x="500" y="389.50504" id="rect2" style="fill:#008000"></rect>
</g>
</svg>
</div>
How i can get the string:
我如何获得字符串:
<rect width="105.71429" height="80" x="351.42856" y="152.36218" id="rect1" style="fill:#008000"></rect>
from this svg. I can use jquery and jquery svg. I try:
从这个svg。我可以使用 jquery 和 jquery svg。我尝试:
$(document).ready(function() {
console.log($("#plan #rect1")[0]);
})
In console i take this string, but i must get string in variable like this:
在控制台中,我使用这个字符串,但我必须像这样在变量中获取字符串:
var str = $("#plan #rect1")[0];
variable str is [object SVGRectElement] [enter link description here]1
变量 str 是 [object SVGRectElement] [在此处输入链接描述] 1
采纳答案by Mordhak
$('#rect1')[0]
This should help. If you want to access tag instead of jQuery element, use [] to get encapsulated element.
这应该有帮助。如果你想访问 tag 而不是 jQuery 元素,使用 [] 来获取封装的元素。
Edit:
编辑:
This should do the trick for you.
The solution explained is to wrap your selection into another tag and call .html() on it to display its content.
解释的解决方案是将您的选择包装到另一个标签中并在其上调用 .html() 以显示其内容。
Don't forget the .clone() call before appending it into your temp div, otherwise you will have some trouble in your html :)
在将其附加到临时 div 之前不要忘记 .clone() 调用,否则您的 html 会遇到一些麻烦:)
回答by Iwo Banas
To combine the previous answers (which were not clear for me at first) the way to get the SVG string is following:
结合之前的答案(一开始我不清楚),获取 SVG 字符串的方法如下:
var str = $('<div>').append($('#plan #rect1').clone()).html();