标头中的行有什么问题?
下面的示例假定创建一个按钮,该按钮每次单击都会增加计数器的数量。但是,我强制两次单击之间延迟2000毫秒。下面的版本有效,但是,如果我使用注释行而不是
document.getElementById("rollButton").onclick=function(){calculation()};
(均在afterWaiting()函数中)
我得到各种奇怪的结果,例如,计数器开始增加的幅度超过1,而等待时间消失了?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function afterWaiting()
{
$("#rollButton").css("color","black");
//$("#rollButton").click(function(){calculation()});
document.getElementById("rollButton").onclick=function(){calculation()};
}
var counter=0;
function calculation()
{
////Enforcing wait:
document.getElementById("rollButton").style.color="red";
document.getElementById("rollButton").onclick="";
window.setTimeout("afterWaiting()",2000);
counter=counter+1;
document.getElementById("test").innerHTML=counter;
}
</script>
</head>
<body>
<button type="button" onclick="calculation()" id="rollButton"> Roll! </button>
<p id="test"> </p>
</body>
</html>
我误会了什么?
提前致谢 :)
JSFiddle:
http://jsfiddle.net/Bwxb9/
最佳答案
唯一需要的代码是
<button type="button" id="rollButton"> Roll! </button>
<p id="test"> </p>
var counter = 0;
var $test = $('#test');
var $rollButton = $('#rollButton');
function increment(){
$test.html(counter++);
$rollButton.off('click', increment);
setTimeout(function(){
$rollButton.on('click', increment);
}, 2000);
}
$rollButton.on('click', increment);
演示:Fiddle
更新:如Andy所建议,但我建议Andy回答,因为它不涉及其他事件处理
var counter = 0;
var $test = $('#test');
var $rollButton = $('#rollButton');
function increment(){
$test.html(counter++);
setTimeout(function(){
$rollButton.one('click', increment);
}, 2000);
}
$rollButton.one('click', increment);
演示:Fiddle