我正在尝试编写一个按钮 - 每次单击它时,它会禁用3秒......但由于某种原因,它会等待一秒钟然后禁用它。你会怎么做才能自动禁用?到目前为止,这是我的一些代码:
function countdown() {
setTimeout(function () {
document.getElementById('btnOne').disabled = null;
}, 4000);
var countdownNum = 4
incTimer();
function incTimer() {
setTimeout(function () {
if (countdownNum != 1) {
countdownNum--;
document.getElementById('timeLeft').innerHTML = 'Click again in ' + countdownNum;
incTimer();
document.getElementById('btnOne').disabled = true;
} else {
document.getElementById('timeLeft').innerHTML = '';
document.getElementById('btnOne').disabled = false;
}
}, 1000);
}
}
答案 0 :(得分:0)
我相信这段代码可以满足您的需求。
<script type="text/javascript">
function fclick(){
document.getElementById('myButton').disabled = true;
setTimeout('countDown(3);', 1000);
}
function countDown(i){
if (i >= 0)
{
document.getElementById('myButton').value = 'Click again in ' + i + ' secs';
i--;
setTimeout('countDown('+i+');', 1000);
}
else
{
document.getElementById('myButton').value = 'Click me';
document.getElementById('myButton').disabled = false;
}
}
</script>
<input type="button" value="Click me" id="myButton" onclick="fclick()">
答案 1 :(得分:0)
这对我有用
<span id="timeLeft"></span>
<input type="submit" id="btnOne" onClick="countdown()">
function countdown() {
document.getElementById('btnOne').disabled = true;
var countdownNum = 3
document.getElementById('timeLeft').innerHTML = 'Click again in ' + countdownNum;
incTimer();
function incTimer() {
setTimeout(function () {
if (countdownNum != 1) {
countdownNum--;
document.getElementById('timeLeft').innerHTML = 'Click again in ' + countdownNum;
incTimer();
document.getElementById('btnOne').disabled = true;
} else {
document.getElementById('timeLeft').innerHTML = '';
document.getElementById('btnOne').disabled = false;
}
}, 1000);
}
}
答案 2 :(得分:0)
您设置的timeout
表示“1秒后,执行X”
你当前的超时实际上很难遵循,但它以一种非常纠结的方式广泛地做到了这一点:
counter
= 4 counter != 1
,则从计数器中减1,禁用按钮,然后返回 2 。否则继续。如您所见,您正在等待1秒后禁用按钮,而不是立即禁用。
我建议更改你的countdown()方法如下:
counter
= 3 counter > 0
,请打印“在counter
秒内再次点击”,从counter
减去1,等待1秒然后返回 2 即可。否则继续。这可能是这样的:(使用你的代码)
的 --- Working Example Here!!! --- 强>
function countdown() {
document.getElementById('btnOne').disabled = true;
//3 is more understandable than 4 for your example.
var countdownNum = 3;
incTimer();
function incTimer() {
if (countdownNum > 0) {
// Order of statements IS important.
// Note the differences in this IF block.
document.getElementById('timeLeft').innerHTML = 'Click again in ' + countdownNum;
countdownNum--;
setTimeout(function(){
// Note that the whole timeout was moved inside,
// Imagine this is recursive function, with a delay.
incTimer();
}, 1000);
} else {
document.getElementById('timeLeft').innerHTML = '';
document.getElementById('btnOne').disabled = false;
}
}
}
有更好的方法来表达您的代码,但我尽可能地坚持您的代码风格。