无法将 svg 元素附加到 svg 根

Unable to append svg element to svg root

我想使用鼠标悬停事件将文本元素添加到我现有的 svg 中。我认为该代码总体上工作正常,但我无法将我创建的文本元素附加到现有的 svg 文件(根)。我尝试以一种我也可以在 stackoverlow 上找到它的方式来做,但它对我不起作用。 var root = doc.documentElementvar root = doc.rootElement 都不起作用。在创建元素时使用 svgNS 或 null 也没有区别。

这是我的代码:

<script type="text/ecmascript">
    <![CDATA[function showText(evt) { 
    var doc = evt.target.ownerDocument; 
    var root = doc.documentElement; 
    var text = doc.createElementNS(null, "text"); 
    text.setAttributeNS(null, "x", "10"); 
    text.setAttributeNS(null, "y", "30"); 
    text.setAttributeNS(null, "font-size", "12"); 
    var textNode = doc.createTextNode("test"); 
    text.appendChild(textNode); 
    root.appendChild(text);  
    }]]>
</script>

我的svg的完整代码:

<?xml version="1.0" encoding="UTF-8" ?>
<svg xmlns="http://www.w3.org/2000/svg" style="stroke:black" height="600" width="800">
  <rect width="800" x="0" y="0" height="600" style="fill:none" />
  <rect width="800" x="0" id="textbox" y="540" height="60" style="fill:none" />
  <rect width="720" x="40" y="30" height="480" style="fill:none" />
  <line y2="510" x1="40" x2="760" y1="510" />
  <line y2="510" x1="40" x2="40" y1="30" />
  <text font-size="12" x="40" y="530">Time (X)</text>
  <text font-size="12" x="5" y="20">Data (Y)</text>
  <polyline style="stroke:black;fill:none;" points="91.84,217.19189757859385 143.68,323.2917668597486 195.52,235.86502103932202 247.36,43.359991864346625 299.2,202.8 351.04,315.903272925833 402.88,160.41241257803188 454.72,157.66691947582518 506.56,387.2047460928005 558.4,183.60000000000002 610.24,260.73963745895736 662.08,59.445816214522495 713.9200000000001,283.88097314947527 "
  stroke-width="2" />
  <script type="text/ecmascript">
    < ![CDATA[function showText(evt) {
      var doc = evt.target.ownerDocument;
      var root = doc.documentElement;
      var text = doc.createElementNS(null, "text");
      text.setAttributeNS(null, "x", "10");
      text.setAttributeNS(null, "y", "30");
      text.setAttributeNS(null, "font-size", "12");
      var textNode = doc.createTextNode("test");
      text.appendChild(textNode);
      root.appendChild(text);
    }]] >
  </script>
  <circle id="circle" text="Dies ist ein Test" r="10" cx="400.0" onmouseover="showText(evt)" cy="510">Dies ist ein Test</circle>
</svg>

SVG 元素必须在 SVG 命名空间中创建,因此您需要:

var text = doc.createElementNS("http://www.w3.org/2000/svg", "text");

您的代码片段所具有的 CDATA begin/end 部分标记中也不能有空格(但您的原始代码摘录没有)。