使用HTML DOM中的JS动态获取SVG <image>元素的'xlink:href'属性

Gre*_*een 11 svg dom xlink

我有一个结构:

<div id="div">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="svg">
        <image x="2cm" y="2cm" width="5cm" height="5cm" id="img" xlink:href="pic.jpg"></image>
    </svg>
</div>
Run Code Online (Sandbox Code Playgroud)

我想得到pic.jpg网址,我需要从最外层的div开始,而不是完全来自source <image>元素:

var div = document.getElementById("div");
var svg = div.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];
var img = svg.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'image')[0];
var url = img.getAttribute('xlink:href');   // Please pay attention I do not use getAttributeNS(), just usual getAttribute()

alert(url);     // pic.jpg, works fine
Run Code Online (Sandbox Code Playgroud)

我的问题是从SVG及其子元素等元素中获取此类属性的正确方法是什么?

因为在我尝试这种方式之前它在Chrome中运行良好(我没有尝试其他浏览器):

var svg = div.getElementsByTagName('svg')[0];   // I do not use NS
var img = svg.getElementsByTagName('image')[0];
var url = img.getAttribute('xlink:href');  // and do not use getAttributeNS() here too

alert(url);     // pic.jpg, works fine
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用时,getAttributeNS()我得到了空白结果:

var svg = div.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];
var img = svg.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'image')[0];

// Please pay attention I do use getAttributeNS()
var url = img.getAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href'); 

alert(url);     // but I got black result, empty alert window
Run Code Online (Sandbox Code Playgroud)

Rob*_*son 25

正确的用法是 getAttributeNS('http://www.w3.org/1999/xlink', 'href');

  • 谢谢!这个答案帮助我*通过JavaScript设置我的SVG内容中的图像的xlink:href属性.我的代码如下:img.setAttributeNS('http://www.w3.org/1999/xlink','href','new.url'); 其中new.url是我想要替换原始图像的url. (5认同)
  • 使用jquery和SVG会给你带来很大的痛苦,最好避免使用. (4认同)