javascript - SVG:加载文档后运行脚本

标签 javascript svg dom-events

我有一个 SVG 文档,我希望能够在其中包含一个脚本(使用 <script> 标签)。在此脚本中,我想设置一个函数,该函数将在文档加载并可供操作时调用。

如果我用 HTML 和 JQuery 做这件事,我会使用 $(document).ready(...) .我希望在 SVG 文档中执行相同的操作,但显然我不能以相同的方式使用 JQuery。

总而言之,我正在寻找的是这样的东西:

测试.svg:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
    <script type="text/ecmascript" xlink:href="myscript.js" />

    <!-- Rest of SVG body goes here -->
</svg>

我的脚本.js:

function init(evt) {
    var svgDocument = evt.target.ownerDocument;
    var svgRoot = svgDocument.documentElement;
    // Manipulate SVG DOM here
}

// --> Somehow attach init() function to onload event of SVG <--

我想尝试在脚本中执行此操作,而不是依赖于明确的 onload="init()"在 SVG 定义中。 (我想编写一个可以包含在多个 SVG 中的脚本,而无需他们了解脚本的工作原理。)

最佳答案

举个例子

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" onload='init(evt)'>
<script type="text/ecmascript">
function init(evt) {
var svgDocument = evt.target.ownerDocument;
var svgRoot = svgDocument.documentElement;
// Do whatever you like on svgRoot to manipulate your SVG DOM
}
</script>
</svg>

关于javascript - SVG:加载文档后运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7667861/

相关文章:

javascript - 如何在新页面上显示计算结果?

javascript - 在 react-redux 中定义函数很奇怪

d3.js - 在 d3 中动态附加形状

JavaScript 事件处理程序 : problem with execution of handler that got parameters

javascript - 在javascript中删除一个字符串,不留空白?

javascript - 在 JavaScript 中使用递归获取范围数

css - 设置 SVG 的后备字体

javascript - 如何在 React 中包含 SVG 文件?

javascript - 在 Javascript 中对输入字段进行分组

javascript - 由 javascript 为 Google map 图例创建的 html 元素的事件监听器不起作用