【发布时间】:2016-06-03 21:17:51
【问题描述】:
我正在尝试学习 JavaScript/jQuery,并且正在尝试创建一个简单的倒计时应用程序。用户可以设置时间量,然后单击显示的值开始倒计时。倒计时发生时,如果用户再次单击显示的值,我想暂停倒计时(请注意,在我的代码中,我只是使用警告消息,因为我还没有开始编写暂停的部分) .到目前为止,一切似乎都奏效了。但是,当倒计时结束时,用户应该能够选择新的倒计时时间并再次单击显示屏以开始倒计时。但是,当我单击显示屏时,它会在开始倒计时之前多次运行警报消息。基本上,用户应该能够在计时器运行时单击显示屏以暂停倒计时。如果倒计时没有运行,那么单击显示屏应该会导致开始新的倒计时。
这是我的 HTML:
<div class="value-display"> <button class="btn" id="increase" onclick="increase()">+</button> <h1 id="display" onclick="startTimer()">5</h1> <button class="btn" id="decrease" onclick="decrease()">-</button> </div>
这是我的 JavaScript:
var total = 5;
var counter;
function increase() {
total += 1;
document.getElementById("display").innerHTML = total;
}
function decrease() {
if (total > 0) {
total -= 1;
document.getElementById("display").innerHTML = total;
}
}
function startTimer() {
counter = setInterval(timer, 1000);
}
function timer() {
if (total === 0) {
document.getElementById("increase").disabled = false;
document.getElementById("decrease").disabled = false;
clearInterval(counter);
return total;
} else if (total > 0) {
total -= 1;
document.getElementById("increase").disabled = true;
document.getElementById("decrease").disabled = true;
document.getElementById("display").innerHTML = total;
$("#display").click(function() {
alert("ok");
})
}
}
这里是代码笔:
【问题讨论】:
-
在 JS 脚本中同时拥有内联事件侦听器和事件侦听器确实无济于事。他们互相冲突。
-
另外,您可以:添加事件侦听器和删除事件侦听器,或者您可以在事件侦听器中添加一个条件来检查计时器。但只是将 add 事件监听器放在条件语句中并不会打开和关闭它。
标签: javascript jquery timer