1

有人可以帮我在一个页面中实现两个 javascript 计数器吗?我目前已经启动并运行了计数器,但是当我尝试为另一个计数器创建一个新的 div 时,原来的计数器消失了,只显示了一个计数器。这是我的第一篇文章,所以请原谅任何混乱的格式。我将不胜感激任何帮助,我对 javascript 很陌生。谢谢!

这是我的代码:

<div id="counter"></div>
<div id="counter1"></div>


<script type="text/javascript">
var START_DATE = new Date("July 27, 2010 13:30:00"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 9001; // 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 = addCommas(count);
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = 
addCommas(count);", msInterval);
}
</script>


<script type="text/javascript">
var START_DATE = new Date("July 27, 2011 13:30:00"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 8001; // 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('counter1').innerHTML = addCommas(count);
setInterval("count += INCREMENT; document.getElementById('counter1').innerHTML =   
addCommas(count);", msInterval);
}
</script>


<script type="text/javascript">
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
</script>
4

1 回答 1

1

你不能有两个window.onload脚本,最后一个会覆盖第一个。

只需重用相同的代码,只需将下一个计数器添加到下一个 div 即可。

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

编辑:只增加一次计数,否则第二个计数器总是在第一个之前

于 2012-06-06T17:01:04.407 回答