在已经运行了几次代码之后,我想再次运行我的代码(倒计时)。
Javascript:
var btn1 = document.getElementById('btn1');
function timer() {
var countdown = 1 * 60 * 1000;
var timerId = setInterval(function() {
countdown -= 1000;
var min = Math.floor(countdown / (60 * 1000));
var sec = Math.floor((countdown - (min * 60 * 1000)) / 1000);
if (countdown <= -1) {
//alert("30 min!");
$(".countTime").html('<div class="countTime"><input type="button" id="btn1" value="Press me!"/></div>');
clearInterval(timerId);
//doSomething();
} else {
if(min > 0) {
$(".countTime").html(min + " : " + sec);
} else {
$(".countTime").html(sec);
}
}
}, 1000); //1000ms. = 1sec.
}
btn1.onclick = timer;
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countTime">
<input type="button" id="btn1" value="Press me!"/>
</div>
它只运行一次。按下按钮并再次运行倒计时不起作用。
最佳答案
问题是;
btn1.onclick = timer;
你必须像这样绑定(bind)点击;
$(document).on("click", btn1, function(){
timer();
});
关于Javascript 再次执行函数(倒计时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44679151/