Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 正在设置JS不工作的SVG元素的属性_Javascript_Html_Svg - Fatal编程技术网

Javascript 正在设置JS不工作的SVG元素的属性

Javascript 正在设置JS不工作的SVG元素的属性,javascript,html,svg,Javascript,Html,Svg,我正在尝试向JS中的SVG元素添加一个xlink:href属性,但它不起作用 这是我的密码: test.html: <html> <head> <script type="text/javascript" src="test.js"></script> </head> <body onload=setupSvgLink()> <object id="test-sv

我正在尝试向JS中的SVG元素添加一个
xlink:href
属性,但它不起作用

这是我的密码:

test.html:

<html>
    <head>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body onload=setupSvgLink()>
        <object id="test-svg" type="image/svg+xml" data="test.svg" />
    </body>
</html>
test.svg:

<?xml version="1.0" standalone="no"?>
<svg version="1.0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="80">
    <a id="waldo"><rect x="10" y="10" width="60" height="60" fill="blue"/></a>
</svg>

我正在用Firefox20测试这一点。我加载
test.html
,但矩形上没有链接。我在Firefox开发者工具的检查器中检查过,元素上确实显示了xlink:href属性,但没有链接

如果我将xlink:href属性添加到SVG文件中,而不是通过JS进行添加,那么效果很好


我做错了什么?

处理SVG时,通常需要使用
元素。setAttributes
,更改函数

function setupSvgLink() {
    var xlinkns="http://www.w3.org/1999/xlink";
    var svg = document.getElementById("test-svg").contentDocument;
    var waldo = svg.getElementById("waldo");
    waldo.setAttributeNS(xlinkns, "href", "waldo.html");
}

只有一个修改:名称空间必须是
http://www.w3.org/1999/xlink
。谢谢@高级指挥官4啊,现在我明白了,我修改了答案。更改以名称空间(如
xlink
)开头的SVG属性时,使用相应的名称空间。否则就是SVG名称空间。你每天都能学到新东西!
function setupSvgLink() {
    var xlinkns="http://www.w3.org/1999/xlink";
    var svg = document.getElementById("test-svg").contentDocument;
    var waldo = svg.getElementById("waldo");
    waldo.setAttributeNS(xlinkns, "href", "waldo.html");
}