1

我正在尝试使用 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> 
4

1 回答 1

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> 
于 2012-05-14T17:37:33.333 回答