bind event handler on keydown listen function Java

2019-08-20 10:58发布

问题:

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

回答1:

declare hits outside your keydown function so it doesn't get reset to 0 each time.



回答2:

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.