如何使用Javascript实时计算?

时间:2015-07-02 05:58:47

标签: javascript jquery html



<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Count up</title>
</head>
<body>



<h1>number 1</h1>
<div id="counter"></div>

<br>

<h1>number 2</h1>
<div id="counter_2"></div>




<script>

    var START_DATE = new Date("July 2, 2015 11:00:00"); // put in the starting date here
    var INTERVAL = 0.366; // in seconds
    var INCREMENT = 1; // increase per tick
    var START_VALUE = 7325698160; // initial value when it's the start date
    var count = 0;

    window.onload = function ()
    {
        var msInterval = INTERVAL * 1000;
        var now = new Date();
        count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
        document.getElementById('counter').innerHTML = count;
        setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = count;", msInterval);
    }




    var START_DATE_2 = new Date("July 2, 2015 11:00:00"); // put in the starting date here
    var INTERVAL_2 = 0.366; // in seconds
    var INCREMENT_2 = 1; // increase per tick
    var START_VALUE_2 = 738160; // initial value when it's the start date
    var count_2 = 0;

    window.onload = function ()
    {
        var msInterval = INTERVAL_2 * 1000;
        var now = new Date();
        count_2 = parseInt((now - START_DATE_2)/msInterval) * INCREMENT_2 + START_VALUE_2;
        document.getElementById('counter_2').innerHTML = count;
        setInterval("count_2 += INCREMENT_2; document.getElementById('counter_2').innerHTML = count_2;", msInterval);
    }
</script>

</body>
</html>
&#13;
&#13;
&#13;

我有这个数字,它只适用于一个数字。然而,当我想要添加更多时,它并没有很好地工作。它只显示第二个功能。有人可以帮帮我吗?非常感谢!!!!

1 个答案:

答案 0 :(得分:2)

用第二个覆盖window.onload处理程序。如果您想为同一事件分配多个事件处理程序,请使用addEventListener方法:

window.addEventListener('load', function() {
    var msInterval = INTERVAL_2 * 1000;
    var now = new Date();
    count_2 = parseInt((now - START_DATE_2) / msInterval) * INCREMENT_2 + START_VALUE_2;
    document.getElementById('counter_2').innerHTML = count;
    setInterval("count_2 += INCREMENT_2; document.getElementById('counter_2').innerHTML = count_2;", msInterval);
});