为什么 getAttributeNS 返回 null?
why is getAttributeNS returning null?
var svg = document.getElementById('test'),
use = svg.lastElementChild;
alert(use.getAttributeNS(null, 'x'));
// "200"
alert(use.getAttributeNS('http://www.w3.org/1999/xlink', 'href'));
// "#shape"
alert(use.getAttributeNS('http://foo.io/bar', 'foo'));
// null - why?
<svg id="test"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:test="http://foo.io/bar">
<defs>
<g id="shape">
<rect x="50" y="50" width="50" height="50" />
<circle cx="50" cy="50" r="50" />
</g>
</defs>
<use xlink:href="#shape" x="200" y="50" test:foo="bar" />
</svg>
查看 MDN 页面,html5 文档似乎不支持命名空间 - https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNS#Example
看来您必须使用 use.getAttribute('test:foo');
var svg = document.getElementById('test'),
use = svg.lastElementChild;
alert(use.getAttributeNS(null, 'x'));
// "200"
alert(use.getAttributeNS('http://www.w3.org/1999/xlink', 'href'));
// "#shape"
alert(use.getAttributeNS('http://foo.io/bar', 'foo'));
// null - why?
<svg id="test"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:test="http://foo.io/bar">
<defs>
<g id="shape">
<rect x="50" y="50" width="50" height="50" />
<circle cx="50" cy="50" r="50" />
</g>
</defs>
<use xlink:href="#shape" x="200" y="50" test:foo="bar" />
</svg>
查看 MDN 页面,html5 文档似乎不支持命名空间 - https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttributeNS#Example
看来您必须使用 use.getAttribute('test:foo');