简体   繁体   English

在keydown侦听函数JavaScript jQuery上绑定事件处理程序

[英]bind event handler on keydown listen function JavaScript jQuery

I am trying to bind a handler to an event. 我试图将处理程序绑定到事件。 The event is a keydown function. 该事件是按键功能。 The handler will listen for hit variables to produce one of two conditions. 处理程序将监听命中变量以产生两个条件之一。 The 1st condition (odd number of hits) will perform 1 function, the 2nd (even number of hits) will perform another function. 第一个条件(命中次数奇数)将执行一项功能,第二个条件(命中次数偶数)将执行另一项功能。 To elaborate, the 1st function will scroll to one element, the 2nd will scroll to another element 详细地说,第一个功能将滚动到一个元素,第二个功能将滚动到另一个元素

FIDDLE 小提琴

Above is a link to a demo, there is a nasty bug which you can see. 上面是一个演示的链接,您可以看到一个讨厌的错误。

The only thing I can think of is that the following should be revised for the second event: 我唯一能想到的是,对于第二个事件,应修改以下内容:

.offset().top

在keydown函数外部声明hits因此不会每次都重置为0。

No, not the condition is in the wrong place but your variable declaration and initialisation. 不,条件不是放在错误的位置,而是您的变量声明和初始化。 If you do 如果你这样做

hits = 0;
if (hits % 2 !== 0) …

the condition will obviously be always false. 条件显然总是错误的。

Move the declaration outside the scope of your event handler function, and don't reset it each time right before you query it. 将声明移到事件处理程序函数的范围之外,并且不要在每次查询之前都重置它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM