我尝试了一些简单的示例,如下所示:
<?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 上看到的,新元素实际上被附加了:
但错误是 - 它没有显示!为什么它被附加但不显示?我在这个问题上花了很多时间,但不知道。
我从 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/