所以我有这个应用程序,我按下开始按钮,然后按钮变为停止按钮。开始按钮将启动并刷新计数器,停止按钮将停止它。
以下是代码:
var sec = 0;
var seconds = 0;
var hundreths = 0;
function timer(x){
return x > 9 ? x : "0" + x;
}
intervalID = setInterval(function(){
seconds = timer(parseInt(sec/60, 10));
hundreths = timer(++sec%60);
$("#time-id").val("Sekundid: "+seconds+" Sajandikud: "+hundreths);
}, 10);
function startTimer(check){
sec = 0;
}
function start(){
changeButton("start");
startTimer(true);
}
function stop(){
changeButton("stop");
startTimer(false);
clearInterval(intervalID);
}
function changeButton(variable){
if(variable === "start"){
var div = document.getElementById("game");
var btn2 = document.createElement("input"); btn2.id = "Stop"; btn2.type = "button"; btn2.value = "Stop";
clearBox("Start");
div.appendChild(btn2);
btn2.onclick = function(){stop()};
}else if(variable === "stop"){
var div = document.getElementById("game");
var btn1 = document.createElement("input"); btn1.id = "Start"; btn1.type = "button"; btn1.value = "Start";
clearBox("Stop");
div.appendChild(btn1);
btn1.onclick = function(){start()};
}
}
window.onload = function (){
var div = document.getElementById("game");
var btn1 = document.createElement("input"); btn1.id = "Start"; btn1.type = "button"; btn1.value = "Start";
div.appendChild(btn1);
btn1.onclick = function (){start()};
};
function clearBox(elementID){
document.getElementById(elementID).remove();
}
<!-- Element removal code -->
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
所以这里的问题是我不知道如何只有按下按钮才能启动计数器。现在它会在页面加载时启动。由于作用域,很难将setInterval放入单独的函数中。
答案 0 :(得分:1)
试试这个:
HTML:
<button onclick='startInterval()'>Start</button>
使用Javascript:
var intervalID;
function startInterval() {
intervalID = setInterval(function(){
seconds = timer(parseInt(sec/60, 10));
hundreths = timer(++sec%60);
$("#time-id").val("Sekundid: "+seconds+" Sajandikud: "+hundreths);
}, 10);
}