我有一个随机倒计时脚本,如下所示:
这是Javascript:
<script>
var timer;
function startCount()
{
timer = setInterval(count, 1000); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count()
{
var do_wait = Math.ceil(4*Math.random());
if (do_wait == 4) {
var rand_no = Math.ceil(4*Math.random()); // 9 = random decrement amount. Counter will decrease anywhere from 1 - 9.
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML);
var newNumber = currentNumber - rand_no;
if (newNumber > 3) {
el.innerHTML = newNumber;
} else {
el.innerHTML = '<font color="white">3</font>'; // This message is displayed when the counter reaches zero.
}
}
}
startCount();
</script>
以下是我在HTML中调用它的方法
<span style="color:white;" id="counter">50</span>
我希望能够在页面上多次显示具有相同倒计时数字的ID“计数器”。问题是每次我显示ID“计数器”时它都有不同的倒计时数字。
答案 0 :(得分:0)
我改变了#id;&#39;为了&#39; name&#39;所以我的文档中没有多次使用相同的id。我在您的代码中做了一些更改:
<html>
<head>
<script>
var timer;
function startCount()
{
timer = setInterval(count, 1000); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count()
{
var do_wait = Math.ceil(4*Math.random());
if (do_wait == 4) {
var rand_no = Math.ceil(4*Math.random()); // 9 = random decrement amount. Counter will decrease anywhere from 1 - 9.
var els = document.getElementsByName('counter');
for(var i = 0 ; i < els.length ; i++) {
var currentNumber = parseFloat(els[i].innerHTML);
var newNumber = currentNumber - rand_no;
if (newNumber > 3) {
els[i].innerHTML = newNumber;
} else {
els[i].innerHTML = '<font color="white">3</font>'; // This message is displayed when the counter reaches zero.
}
}
}
}
startCount();
</script>
</head>
<body>
<span style="color:white;" name="counter">50</span>
<span style="color:white;" name="counter">50</span>
<span style="color:white;" name="counter">50</span>
<span style="color:white;" name="counter">50</span>
</body>
我现在使用计数器作为名称属性的值,使用 document.getElementsByName()来读取这些名称数组。 顺便说一下,我在Chrome中测试过。