bind event handler on keydown listen function JavaScript jQuery

喜你入骨 提交于 2019-12-11 14:05:13

问题


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.



来源:https://stackoverflow.com/questions/12993188/bind-event-handler-on-keydown-listen-function-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!