javascript - document.documentElement.appendChild() 不起作用

标签 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>

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

Screenshot of Firebug

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

我从 SVG 研讨会复制了这个示例,并在 Chrome 和 Firefox 中进行了尝试。

请帮忙:/

最佳答案

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

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

关于javascript - document.documentElement.appendChild() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11889527/

相关文章:

javascript - Rails SweetAlert 2 无法在 ie11 中工作

javascript - 如何更改按钮的大小并为其添加背景颜色?

javascript d3 刻度格式

javascript - d3js 图形代码以不同的顺序显示不同数据的 y 轴

SVG定位

javascript - 如何制作带有矩形 SVG 图标的方形图标按钮

javascript - d3.js/svg - 如何动态地将文本附加到我的弧线

javascript - 如何为 HTML textarea 元素的某些内部文本设置背景颜色?

javascript - 检查是否使用 jQuery 加载了图像(没有错误)

javascript - 如何获取缩小的 javascript 堆栈跟踪并针对源映射运行它以获得正确的错误?