问题
What I am trying to do is to set the Javascript script reference in an embedded SVG document dynamically from Javascript code within the HTML.
I assumed it would be just as easy as dynamically appending a node to an appropriate place in the embedded SVG document.
I found that the node was actually added at runtime (can check this with Firefox Inspect Element), but the Javascript code contained in the reference is not executed when it needs to be.
Anybody have an idea about this? Does anything else need to be done to get the SVG to be able to call functions in the Javascript code?
Here is a simplified scenario:
test.html (embeds the 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>
embed.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>
and finally the external Javascript I am trying to dynamically assign (script.js)
function MyFunction() {
alert("I can execute script!");
}
回答1:
SVG elements must be created in the svg namespace which is http://www.w3.org/2000/svg so instead of createElement you must use createElementNS similarly for the xlink attribute it must go in the xlink namespace so you need
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");
来源:https://stackoverflow.com/questions/16626556/how-to-get-a-working-dynamic-javascript-reference-in-an-svg