获取命名空间声明属性值的正确方法
考虑一下 SVG/XML 和 JavaScript:
<svg id="foo" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<use id="bar" xlink:href="#whee" />
</svg>
...
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var xlnk = foo...; // What is correct here?
var link = bar.getAttributeNS(xlnk,'href');
显然我可以使用 xlnk = "http://www.w3.org/1999/xlink"
; 来完成这项工作;但是,我的问题是动态获取 svg
元素上的 xmlns:xlink
属性的正确方法是什么?
以下代码恰好可以在 Safari/Chrome/FF 中运行,但它真的有效吗?var xlnk = foo.getAttribute('xmlns:xlink');
以下代码在这些浏览器中返回空字符串:var xlnk = foo.getAttributeNS("http://www.w3.org/2000/svg", "xlink");
Consider this SVG/XML and JavaScript:
<svg id="foo" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<use id="bar" xlink:href="#whee" />
</svg>
...
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var xlnk = foo...; // What is correct here?
var link = bar.getAttributeNS(xlnk,'href');
Clearly I can make this work with xlnk = "http://www.w3.org/1999/xlink"
; my question, however, is what is the correct way to dynamically fetch the xmlns:xlink
attribute on the svg
element?
The following code happens to work in Safari/Chrome/FF, but is it really valid?var xlnk = foo.getAttribute('xmlns:xlink');
The following code returns an empty string in those browsers:var xlnk = foo.getAttributeNS( "http://www.w3.org/2000/svg", "xlink" );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
getAttributeNS()
规范将第二个参数记录为:根据 XML 中的命名空间,第三版,
xmlns
前缀是保留并用作PrefixedAttName
定义NSAttName.
由于
NSAttName
没有“本地部分”,并且没有QName
确实如此 - 似乎xmlns:xlink
不被视为命名空间+本地名称,而是属性名称本身。由于这与通常符合标准的浏览器的实验结果一致,因此我确信以下代码是有效且正确的:The
getAttributeNS()
specification documents the second parameter as:Per Namespaces in XML, 3rd Edition the
xmlns
prefix is reserved and used as part of thePrefixedAttName
to define anNSAttName
.Since a
NSAttName
does not have a "local part"—and aQName
does—it seems thatxmlns:xlink
is not considered a namespace+local name, but is rather the attribute name itself. As this is consistent with the experimental results across normally-standards-compliant browsers, I am convinced that the following code is valid and correct: