SVG 元素的外层 HTML [英] outerHTML of an SVG element
问题描述
为什么我们不能通过 element.outerHTML
属性获取 svg 元素的 outerHTML?
Why can not we get outerHTML of an svg element with element.outerHTML
property?
这种方式是获取 svg 源代码的最佳http://jsfiddle.net/33g8g/?
Is this way is the best http://jsfiddle.net/33g8g/ for getting svg source code?
推荐答案
它不能通过 externalHTML 访问,因为 SVG 不是 HTML -- 它是一个单独的 XML 规范.
It's not accessible via outerHTML because SVG is not HTML -- it's a separate XML specification.
例如,这就是为什么该示例中的 svg 节点定义了自己的命名空间 (xmlns="http://www.w3.org/2000/svg
).
That's why, for example, your svg node in that example has its own namespace defined (xmlns="http://www.w3.org/2000/svg
).
对于一次性查询而言,您的示例可能是最方便的,但实际上可以使用本机属性进行挖掘.只是需要做更多的工作.
Your example may be the most expedient for a one-off query, but it's actually possible to dig in using native attributes. It just takes a bit more work.
让我们使用链接的示例节点:
Let's use the linked sample node:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<text x="0" y="15" fill="black">An SVG element.</text>
</svg>
如果要提取命名空间和版本,请使用 attributes
属性.
If you want to extract the namespace and version, use the attributes
property.
var svgElement = $('svg')[0]; // using your example
console.log(svgElement.attributes.xmlns); // outputs "http://www.w3.org/2000/svg"
console.log(svgElement.attributes.version); // outputs "1.1"
如果要提取实际内容,请迭代子项.与上述类似,非文本节点的 attributes
集合将包含 x/y 值(等).
If you want to extract the actual contents, iterate over the children. Similar to the above, a non-text node's attributes
collection will contain the x/y values (etc).
不使用 jQuery,再次使用您的示例:
Without using jQuery, using your example again:
for (var i = 0; i < svgElement.childNodes.length; i++) {
var child = svgElement.childNodes[i];
if (child.nodeType == 1) {
console.log(child.attributes[0].name); // "x"
console.log(child.attributes[0].value); // "0"
console.log(child.attributes[1].name); // "y"
console.log(child.attributes[1].value); // "15"
}
}
这是一个更新的 Fiddle,更优雅地展示了可能性:http://jsfiddle.net/33g8g/8/
Here's an updated Fiddle, a bit more elegantly demonstrating the possibilities: http://jsfiddle.net/33g8g/8/
这篇关于SVG 元素的外层 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!