所以,我试图制作一个番茄钟,并且我的变量没有更新。我创建了按钮,当单击时增加或减少变量工作时间,但是当我调用我的startTimer函数时,我的变量workTime仍然是它最初设置的原始值。如何使变量更新为正确的数量。
这是我的Codepen链接。 http://codepen.io/jerardov/pen/Xbvbpo
CSS
$(document).ready(function() {
//variables//
workTime = 25;
time = workTime * 60;
breakLength = 5;
//update variables
$(".breakMinus").click(function() {
if (breakLength > 0) {
breakLength -= 1;
$(".breakLength").text(breakLength);
}
})
$(".breakPlus").click(function() {
breakLength += 1;
$(".breakLength").text(breakLength);
})
$(".workMinus").click(function() {
if (workTime > 0) {
workTime -= 1;
$(".workTime").text(workTime);
$("#time").text(workTime);
}
})
$(".workPlus").click(function() {
workTime += 1;
$(".workTime").text(workTime);
$("#time").text(workTime);
})
//click//
$(".start").click(function() {
display = $('#time');
startTimer(time, display);
})
//display//
$(".workTime").text(workTime);
$(".breakLength").text(breakLength);
$("#time").text(workTime);
console.log(workTime);
console.log(secondS);
//start time function//
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
});
HTML
<h1>Adjust Work Time</h1>
<div class="workTime"></div>
<button class="btn btn-success workMinus">-</button>
<button class="btn btn-success workPlus">+</button>
<h1>Break Time</h1>
<div class="breakLength"></div>
<button class="btn btn-success breakMinus">-</button>
<button class="btn btn-success breakPlus">+</button>
<h1>Clock</h1>
<div><span id="time"></span>
</div>
<button class="btn btn-success start">start</button>
<div class=""></div>
答案 0 :(得分:1)
代码中的缺陷很少;
&#39;计时器&#39;更改工作时间/中断持续时间时,不会更新变量。因此,当调用Start计时器时,它使用原始值。因此,这个错误。
使用JSlint检查代码是否有良好的JavaScript实践。