2

I tried some simple examples like the following one:

<?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>

This one shows a rectangle and if you click, test() gets executed (see running version here). As I see on the DOM with Firebug, the new element gets actually appended:

Screenshot of Firebug

But the error is - it does not get showed! Why does it get appended but not shown? I've spent so much time in this problem, but no idea.

I copied this example out of a SVG workshop and I tried it in Chrome and Firefox.

Please help :/

4

1 回答 1

5

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

var t = document.createElementNS('http://www.w3.org/2000/svg', 'text');
于 2012-08-09T18:29:13.600 回答