为什么我的动态创建的<use>元素没有显示?

时间:2017-10-05 11:21:10

标签: javascript jquery svg

使用JavaScript和jQuery我试图用链接到另一个组元素的use元素替换group元素。

&#13;
&#13;
// Javascript
origgroup = $("#origgroup")[0];
repgroup = $("#referenceGroup1")[0];
origgroupParent = origgroup.parentNode;

use = document.createElementNS("http://www.w3.org/2000/svg", "use");
use.setAttribute("xlink:href", "#origgroup2");
use.setAttribute("id", "newuse");

tmp = origgroupParent.replaceChild(use, origgroup);

// After this snippet is run, "targetsvg" and "control" are identical. Except that targetsvg's use-tag has an unique ID.
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- My "atlas". I want to put <use> elements in "targetsvg" below, linking to these groups. -->
Atlas <br>
<svg id="atlas" width="120" height="70" version="1.1">
  <g id="referenceGroup1">
    <rect x="10" y="10" width="90" height="20" fill="green"/>  
    <circle cx="20" cy="40" r="15" fill="blue"/>
  </g>
  <g id="referenceGroup2">
    <rect x="40" y="10" width="90" height="20" fill="red"/>  
    <circle cx="50" cy="40" r="15" fill="orange"/>
  </g>
</svg>
<br> Target <br>
<!-- My target -->
<svg id="targetsvg" width="120" height="70" version="1.1"
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <g id="origgroup">
    <rect x="40" y="10" width="90" height="20" fill="red"/>  
    <circle cx="50" cy="40" r="15" fill="orange"/>
  </g>
</svg>
<br>
Control
<br>
<!-- This is identical to the javascript modified version of "targetsvg" -->
<svg id="control" width="120" height="70" version="1.1" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <use xlink:href="#referenceGroup1"></use>
</svg>
&#13;
&#13;
&#13;

我期望发生的事情是在&#34;目标&#34;下面有一个蓝色圆圈和一个绿色矩形。如果我检查结果svg&#34; targetsvg&#34;它与&#34; Control&#34;下的svg完全相同。这让我相信&#34; targetsvg&#34;由于某种原因没有重新绘制,这是正确的吗?有没有办法强迫它?

我花了最近五个小时搜索,但我找不到类似的东西。我找到的最相关的是 SVG <use> in Chrome doesn't work 但是那使用了Angular,我不是。我认为原因是相同的(&#34;元素中的相对散列链接无法正确解析。&#34;)。但如果是这种情况,如何在没有Angular的情况下解决这个问题?

谢谢!

[背景:我有一个由illustrator生成的巨大svg文件。在这个文件中有许多相当复杂的元素(组et.c.),我需要有不同的版本。这些元素需要出现在最终结果的多个位置,所以我要么需要有多个副本(根据具体情况显示/隐藏)或某种类型的“地图集”。我挑选和替换的地方。我的直觉说后者将更易于维护,因为至少有四个地方和七个&#34;版本&#34; (想想&#34;绿色&#34;,&#34;绿色,符号x&#34;,&#34;红色,符号为y&#34; et.c.)。如果还有其他选择,我欢迎这些。]

1 个答案:

答案 0 :(得分:1)

发布后几分钟,我意识到这是一个命名空间问题。将JavaScript更改为:

origgroup = $("#origgroup")[0];
repgroup = $("#referenceGroup1")[0];
origgroupParent = origgroup.parentNode;

// Namespaces
var svgns = 'http://www.w3.org/2000/svg',
xlinkns = 'http://www.w3.org/1999/xlink'

use = document.createElementNS(svgns, "use");
// **setAttributeNS** instead of setAttribute as originally.
use.setAttributeNS(xlinkns, "xlink:href", "#referenceGroup1");
use.setAttribute("id", "newuse");

tmp = origgroupParent.replaceChild(use, origgroup);

解决了我的问题。

相关问题