document.documentElement.appendChild()不起作用

Flo*_*ler 2 javascript svg

我尝试了一些简单的例子,如下所示:

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <script type="text/javascript">
    <![CDATA[

      function test() {
        var svgElement = document.documentElement;
        var tnode = document.createTextNode('thx for the click');
        var t = document.createElement('text');
        t.setAttribute('x','20');
        t.setAttribute('y','32');
        t.setAttribute('class','ext');
        t.setAttribute('id','text1');
        t.appendChild(tnode);
        svgElement.appendChild(t);
      }
    ]]>
    </script>
  </defs>
  <rect width="100" height="100" y="50" x="50" onclick="test();" />
</svg>
Run Code Online (Sandbox Code Playgroud)

这个显示一个矩形,如果单击,test()将被执行(请参阅此处运行的版本).正如我在使用Firebug的DOM上看到的那样,实际附加了新元素:

Firebug的屏幕截图

但错误是 - 它没有显示出来!为什么会附加但不显示?我在这个问题上花了很多时间,但不知道.

我从SVG研讨会中复制了这个例子,我在Chrome和Firefox中尝试过它.

请帮忙 :/

Rob*_*son 5

您需要在SVG名称空间中创建元素,即

var t = document.createElementNS('http://www.w3.org/2000/svg', 'text');
Run Code Online (Sandbox Code Playgroud)