在 jQuery 中调用一次事件后,如何防止该事件重复发生?
现在,我已经掌握了它,以便您可以按向左箭头键来执行事件(事件 1)。如果在该事件之后按右箭头键,它将执行另一个事件(事件 2)。
如何限制它,以便如果按两次左箭头键,就不会重复事件 1?
现在,我有:
$(document).keydown(function(f){
if (f.keyCode == 39) {
// do event 1 here with the left arrow key
}
$(this).keydown(function(f){
if (f.keyCode == 39) {
// do event 2 with the right arrow key
window.location.href = "index.php";
}
});
我是否需要将变量设置为 false,然后在事件 1 完成后设置为 true?
Right now, I've got it so that you can press the left arrow key to perform an event (event 1). If you press the right arrow key after that event, it will perform another event (event 2).
How can I restrict it so that if the left arrow key is pressed twice, it won't repeat event 1?
Right now, I've got:
$(document).keydown(function(f){
if (f.keyCode == 39) {
// do event 1 here with the left arrow key
}
$(this).keydown(function(f){
if (f.keyCode == 39) {
// do event 2 with the right arrow key
window.location.href = "index.php";
}
});
Do I need to set a variable set to false and then true after event 1 has completed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行代码后,使用
$(this).unbind('keydown')
删除处理程序。PS:通常您会使用
.one()
方法来处理一次性事件,但由于该事件也会在您不想解除绑定的情况下触发(已使用不同的键)按下),需要手动解绑。Use
$(this).unbind('keydown')
to remove the handler after your code has been executed.PS: Usually you'd use the
.one()
method for a one-time event, but since the event also fires in cases where you don't want to unbind it (a different key has been pressed), you need to do the unbinding manually.