获取javascript写入变量而不是document.write

时间:2013-10-03 13:58:50

标签: javascript variables timestamp document.write

我有以下打印时间戳的javascript:

<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(hours + "" + minutes + seconds + month + "" + day + "" + year)
//-->
</script>

但是我想在页面的很多地方使用这个时间戳,我怎么称它为$ timestamp所以我可以控制它放在哪里?

提前致谢。

2 个答案:

答案 0 :(得分:1)

设置变量,例如:

var timestamp = hours + "" + minutes + seconds + month + "" + day + "" + year;

以后在代码中使用该变量来显示页面中的信息,例如:

var container = document.getElementById('container1');
container.innerHTML = timestamp;

其中'container1'是一个html元素,如span,div,p等ex:

<span id="container1"></span>

答案 1 :(得分:0)

回答

<script>
    function startTime()
    {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    // add a zero in front of numbers<10
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML=h+":"+m+":"+s;
    t=setTimeout('startTime()',500);
    }

    function checkTime(i)
    {
    if (i<10)
    {
    i="0" + i;
    }
    return i;
    }
</script>
<span id="txt"></span>
<script type="text/javascript">
  startTime().swap('txt');
</script>