标题中的行有什么问题?
下面的示例假设制作一个按钮,该按钮在每次单击时都会递增计数器。但是,我强制两次单击按钮之间的延迟为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/
发布于 2013-02-23 21:42:03
唯一需要的代码是
<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
发布于 2013-02-23 21:41:20
不同之处在于,当您像在原始版本中那样通过onclick应用事件处理程序时,您只能将一个处理程序绑定到元素。而使用onclick=""可以清除它。
使用jQuery .click(handler)时,每次调用它都会绑定一个新的处理程序(并且可以使用unbind('click') (而不是onclick="")解除绑定。因此,在对afterWaiting进行了几次调用之后,您已经在元素上应用了多次单击处理程序,并且在每次单击时,calculation函数都会运行多次。
因此,纠正它的一种方法是替换
document.getElementById("rollButton").onclick=""; 使用
$('#rollButton').unbind('click');发布于 2013-02-23 21:40:38
这通常是一种奇怪和令人困惑的方法。下面是我如何做到这一点,而不是过多地混用jquery和纯js (onclick):
http://jsfiddle.net/LGvKS/
var wait = false;
counter = 0;
$('button').click(function(){
if(!wait){
$('span').text(++counter);
wait=true;
setTimeout(function(){
wait=false;
},2000);
}
});https://stackoverflow.com/questions/15041088
复制相似问题