gpt4 book ai didi

Javascript 再次执行函数(倒计时)

转载 作者:行者123 更新时间:2023-11-28 04:30:13 28 4
gpt4 key购买 nike

在已经运行了几次代码之后,我想再次运行我的代码(倒计时)。

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();
});

https://jsfiddle.net/a9txuLhd/

关于Javascript 再次执行函数(倒计时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44679151/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com