2013-10-02 107 views
5

我从JavaScript动态创建SVG元素。对于像矩形这样的可视化对象来说它工作得很好,但是我在生成有效的xlinks时遇到了麻烦。在下面的例子中,第一个矩形(这是静态定义的)在点击时正常工作,但另外两个(在JavaScript中创建)忽略点击...即使检查Chrome中的元素似乎显示相同的结构。在JavaScript中动态创建SVG链接

我已经看到多个类似的问题出现,但没有一个确切地解决这个问题。我发现最近的是[adding image namespace in svg through JS still doesn't show me the picture],但这不起作用(如下所述)。我的目标是纯粹用JavaScript来完成,而不依赖于JQuery或其他库。


<!-- Static - this rectangle draws and responds to click --> 
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="svgTag"> 
    <a xlink:href="page2.html" id="buttonTemplate"> 
     <rect x="20" y="20" width="200" height="50" fill="red" class="linkRect"/> 
    </a> 
</svg> 

<script> 
    var svgElement = document.getElementById ("svgTag"); 

    // Dynamic attempt #1 - draws but doesn't respond to clicks 
    var link = document.createElementNS("http://www.w3.org/2000/svg", "a"); // using http://www.w3.org/1999/xlink for NS prevents drawing 
    link.setAttribute ("xlink:href", "page2.html"); // no improvement with setAttributeNS 
    svgElement.appendChild(link); 

    var box = document.createElementNS("http://www.w3.org/2000/svg", "rect"); 
    box.setAttribute("x", 30); 
    box.setAttribute("y", 30); 
    box.setAttribute("width", 200); 
    box.setAttribute("height", 50); 
    box.setAttribute("fill", "blue"); 
    link.appendChild(box); 

    // Dynamic attempt #2 (also draws & doesn't respond) - per https://stackoverflow.com/questions/6893391 
    box = document.createElementNS("http://www.w3.org/2000/svg", "rect"); 
    box.setAttribute("x", 40); 
    box.setAttribute("y", 40); 
    box.setAttribute("width", 200); 
    box.setAttribute("height", 50); 
    box.setAttribute("fill", "green"); 
    box.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', "page2.html"); 
    svgElement.appendChild(box); 

+0

每在链接的评论,我曾与setAttributeNS尝试它。但是,看起来问题是我使用了错误的命名空间(svg而不是xlink)。 – user2837568

回答

7

只有一个<a>可以如此加入的xlink的链接:href属性的<rect>元件将没有任何效果。

你需要使用setAttributeNS,你说不起作用,但它对我来说可能是有一些其他问题。

这个例子对我的作品:

var svgElement = document.getElementById ("svgTag"); 
 

 
var link = document.createElementNS("http://www.w3.org/2000/svg", "a"); 
 
link.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', "page2.html"); 
 
svgElement.appendChild(link); 
 

 
var box = document.createElementNS("http://www.w3.org/2000/svg", "rect"); 
 
box.setAttribute("x", 30); 
 
box.setAttribute("y", 30); 
 
box.setAttribute("width", 200); 
 
box.setAttribute("height", 50); 
 
box.setAttribute("fill", "blue"); 
 
link.appendChild(box);
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="svgTag"> 
 
</svg>

+1

谢谢,这确实解决了它。看起来问题是,当我以前尝试createElementNS时,我使用了错误的名称空间:http://www.w3.org/2000/svg而不是http://www.w3.org/2000/svg。我(不正确)的想法是,“a”元素是sag命名空间的一部分,现在我看到名称空间应该在属性级别(xlink)确定。 – user2837568