标题中的行有什么问题?
下面的示例应该创建一个按钮,每次单击该按钮时都会增加一个计数器。但是,我在按钮单击之间强制执行 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/
最佳答案
不同之处在于,当您像在原始版本中一样通过 onclick
应用事件处理程序时,您只能将一个处理程序绑定(bind)到该元素。并使用 onclick=""
来清除它。
当使用 jQuery .click(handler)
时,每次调用它时都会绑定(bind)一个新的处理程序(并且您可以使用 unbind('click')
取消绑定(bind)它 (< em> 而不是使用 onclick=""
)。因此,在几次调用 afterWaiting
后,您已经在元素上应用了多个点击处理程序,并且在每个单击计算
函数运行多次..
因此,纠正它的一种方法是替换
document.getElementById("rollButton").onclick="";
与
$('#rollButton').unbind('click');
关于javascript - $ ("#id").click(函数(){计算()});,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15041088/