SVG文档中的getElementById

mer*_*esi 5 javascript svg getelementbyid

我写了一个这样的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 .....
Run Code Online (Sandbox Code Playgroud)

如注释行中的alert(document);警报[object SVG document]

但:

var path=document.getElementById('path1');
alert(path);
Run Code Online (Sandbox Code Playgroud)

警报null

我还尝试将svg放在html页面和xhtml页面中,尝试了更多操作,但暂时没有结果。

任何的想法?

pim*_*vdb 5

在您致电时var path=document.getElementById('path1');path1尚未定义(稍后会介绍)。

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

但是我不确定是否可以将<script>标记放在内<svg>

  • @pimvdb:在&lt;svg&gt;内部的任何地方都允许使用&lt;script&gt;。 (2认同)

jbe*_*rd4 5

只是为了补充pimvdb的答案:

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

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