通过创建毫秒,秒和分钟的变量,我想制作一个小秒表项目。我所拥有按钮的onClick
适用于theTimer()
:
var milli = 0;
var seconds = 0;
var minutes = 0;
var onOff = 0;
var txtMilli = document.getElementById("txtMilli");
var txtSeconds = document.getElementById("txtSeconds");
var txtMinutes = document.getElementById("txtMinutes");
function theTimer()
{
if (onOff == 0) {
onOff = 1;
timer = setInterval("startCounting()",1);
}
if (onOff == 1) {
onOff == 0;
clearInterval(timer);
}
}
function startCounting()
{
if (milli >999)
{
milli = 0; if (seconds <60) {seconds +=1}
}
else
{
milli +=1;
}
if (seconds >59)
{
seconds = 0; minutes += 1;
}
if (milli > 10)
{
txtMilli.innerHTML = "0" + milli;
}
if (milli < 10)
{
txtMilli.innerHTML = "" + milli;
}
}
控制台中没有显示任何内容,问题是DIV
在运行时永远不会从0更改。
答案 0 :(得分:1)
我设法像这样修复你的代码:
var milli = 0;
var seconds = 0;
var minutes = 0;
var onOff = 0;
var txtMilli = document.getElementById("txtMilli");
var txtSeconds = document.getElementById("txtSeconds");
var txtMinutes = document.getElementById("txtMinutes");
function startCounting(){
if (milli >999) { milli = 0; if (seconds <60) {seconds +=1} }
else {milli +=1;}
if (seconds >59) {seconds = 0; minutes += 1;}
if (milli > 10) {txtMilli.innerHTML = "0" + milli;}
if (milli < 10) {txtMilli.innerHTML = "" + milli;}
}
function theTimer(){
if (onOff == 0) {
onOff = 1;
timer = setInterval(startCounting, 1);
} else if (onOff == 1) {
onOff = 0;
clearInterval(timer);
}
}
myButton.onclick = theTimer;
theTimer
中有一个错误,您将onOff
设置为1
,然后立即检查它是否为1
并将其重新设置为{{} 1}}。我使用0
修复此问题。
我还将else if
(这是一个比较)更改为onOff == 0
(这是一项作业)。
使用JSFiddle:https://jsfiddle.net/k83tvfhc/