1

我要做的是从 HTML 中的 Javascript 代码动态地在嵌入式 SVG 文档中设置 Javascript 脚本引用。

我认为这与将节点动态附加到嵌入式 SVG 文档中的适当位置一样简单。

我发现该节点实际上是在运行时添加的(可以使用 Firefox Inspect Element 检查),但是引用中包含的 Javascript 代码在需要时没有执行。

有人对此有想法吗?是否需要做任何其他事情才能使 SVG 能够调用 Javascript 代码中的函数?

这是一个简化的场景:

test.html(嵌入 SVG)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
    function ActivateScript() {
      var svgdoc = document.getElementById("svg");
      var newref = svgdoc.contentDocument.createElement('script');
      newref.setAttribute("type", "text/javascript");
      newref.setAttribute("xlink:href", "script.js");
      svgdoc.contentDocument.documentElement.appendChild(newref);
    }
</script>
</head>
<body>
<input type="button" value="Activate script" onclick="ActivateScript()" />
<object id="svg" type="image/svg+xml" data="embed.svg"/>
</body>
</html>

嵌入.svg

<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="12cm" height="12cm" xmlns:xlink="http://www.w3.org/1999/xlink">
<g style="fill-opacity:1; stroke:black; stroke-width:0.1cm;">
<circle cx="6cm" cy="2cm" r="100" style="fill:red;" transform="translate(0,50)" onclick="MyFunction()"/>
</g>
</svg>

最后是我试图动态分配的外部Javascript(script.js)

function MyFunction() {
alert("I can execute script!");
}
4

1 回答 1

2

SVG 元素必须在 svg 命名空间中创建,http://www.w3.org/2000/svg因此您必须使用 createElementNS 而不是 createElement

  var newref = svgdoc.contentDocument.createElementNS('http://www.w3.org/2000/svg', 'script');
  newref.setAttribute("type", "text/javascript");
  newref.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "script.js");
于 2013-05-18T16:46:50.483 回答