有人可以幫助我在單個頁面內實現兩個JavaScript計數器嗎?我目前有計數器正在運行,但是當我嘗試爲另一個計數器創建一個新的div時,原始計數器消失並且只顯示一個計數器。這是我的第一篇文章,請原諒任何搞砸的格式。我會非常感謝任何幫助,我很新的JavaScript。謝謝!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>
你不能只是再次複製代碼。所有這些變量都有相同的名稱!至少,您需要使用不同的變量名稱來定義第二個計數器。 – sachleen