简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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