javascript SVG 文档中的 getElementById

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6817500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:57:33  来源:igfitidea点击:

getElementById in SVG document

javascriptsvggetelementbyid

提问by merveotesi

I wrote a svg file like this:

我写了一个像这样的svg文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg width="1280pt" height="650pt" viewBox="0 0 1280 650" id="svg1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><script xlink:href="pathToPolyline.js"/><script><![CDATA[

alert(document);//returns [object SVG document]

//and tried

var path=document.getElementById('path1');//the problem line

alert(path);

]]></script>
<path id="path1" fill="#000000" d=" M 0.00 0.00 L 1280.00 0.00 L 1280.00 449.99 C 1276.46 444.19 1270.19 441.08 1265.59 436.31 C 1264.17 429.73 1265.36 422.91 1266.42 416.36 C 1267.19 413.43 1264.94 410.65 1262.45 409.42 C 1255.44 405.63 1247.99 402.68 12 .....

As in the comment line alert(document);alerts [object SVG document].

如评论行中的alert(document);警告[object SVG document]

But:

但:

var path=document.getElementById('path1');
alert(path);

alerts null.

警报null

I also tried to put svg in an html page, also in an xhtml page, tried more thing but no result for now.

我还尝试将 svg 放在一个 html 页面中,也在一个 xhtml 页面中,尝试了更多的东西,但现在没有结果。

Any idea?

任何的想法?

采纳答案by pimvdb

At the time you call var path=document.getElementById('path1');, the path1is not defined yet (it comes later on).

在您调用 时var path=document.getElementById('path1');path1尚未定义(稍后会出现)。

You ought to put the code after the path definition.

您应该将代码放在路径定义之后。

However I'm not sure if you can put <script>tags inside a <svg>.

但是我不确定您是否可以将<script>标签放入<svg>.

回答by jbeard4

Just to supplement pimvdb's answer:

只是为了补充 pimvdb 的回答:

You can use script tags in SVG: http://www.w3.org/TR/SVG11/script.html

您可以在 SVG 中使用脚本标签:http: //www.w3.org/TR/SVG11/script.html

Furthermore, you can use jQuery 1.2.6 with pure SVG documents, or any version of jQuery if you're using an HTML document with embedded SVG. In this case, you would be able to put your script tag wherever you like, and then use jquery's $(document).readymethod to run the scripts after the document has been loaded.

此外,您可以将jQuery 1.2.6 与纯 SVG 文档或任何版本的 jQuery 一起使用(如果您使用的是带有嵌入式 SVG 的 HTML 文档)。在这种情况下,你可以把你的脚本标签放在任何你喜欢的地方,然后在文档加载后使用 jquery 的$(document).ready方法来运行脚本。