gpt4 book ai didi

javascript - 防止按下多个按钮

转载 作者:行者123 更新时间:2023-11-28 12:02:33 25 4
gpt4 key购买 nike

我有一个通过按钮激活的简单倒计时。使用 onclick 我开始操作,但我注意到,如果您继续按下按钮,它会增加时间,并且倒计时不同步。我该如何防止这种情况发生,并且一次只允许一次点击?

  var count = 10,
startcounter = document.getElementById("stercount");

startcounter.onclick = function() {
countdown = setInterval(function(){
document.getElementById("countdown").innerHTML = count + " seconds remaining!";
if (count <= 0) {
clearInterval(countdown);
document.getElementById("countdown").innerHTML = "Done!";
}
count--;
}, 1000);
};

演示:http://jsfiddle.net/StWXk/1/

最佳答案

将标志变量isClicked默认设置为false。单击按钮时,将 isClicked 设置为 true。在 click 事件期间,如果 isClickedtrue 则使其返回 false

var isClicked = false;  
var count = 10,
startcounter = document.getElementById("stercount");

startcounter.onclick = function() {
if(isClicked) return false;

isClicked = true;
countdown = setInterval(function(){
document.getElementById("countdown").innerHTML = count + " seconds remaining!";
if (count <= 0) {
clearInterval(countdown);
document.getElementById("countdown").innerHTML = "Done!";
}
count--;
}, 1000);
};​

演示:http://jsfiddle.net/StWXk/2/

关于javascript - 防止按下多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13898140/

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