将当前时间写入SVG文档

时间:2012-05-14 15:50:38

标签: javascript svg

我正在尝试使用ECMAScript将当前时间添加到SVG文件中。 以下是我的代码。不幸的是它不起作用。我该如何解决?

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"   width="300" height="300">
<text x="0" y="15" fill="red">It is now
<script type="text/javascript">
<![CDATA[
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
document.write(month + "/" + day + "/" + year);
]]>
</script>
</text>
</svg> 

1 个答案:

答案 0 :(得分:2)

演示:http://jsfiddle.net/M8YXS/

<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300">
  <text x="0" y="15" fill="red">It is now <tspan id="now">(time)</tspan></text>

  <!--
    This script block must either be after the element in the source code
    or else the code below must be wrapped in a callback that is invoked
    only after the DOM is created (e.g. window.onload in a browser)
  -->
  <script>
    // Create whatever string you want
    var dateString = (new Date).toDateString();

    // Set the string content of the Text Node child of the <tspan>
    document.getElementById('now').firstChild.nodeValue = dateString;
  </script>
</svg>