I am using the jQuery hotkeys plugin to bind some keypresses to events. I tried to change this to bind looping over an array instead, but it’s not working.
var letters = ["a","b","c"];
for (var x in letters)
{
var letter = letters[x];
$("el").bind('keydown', letter, function() { /*...*/ })
.bind('keyup', letter, function() { /*...*/ });
}
This code binds all events to the last letter in the array (“c”) and none to others. Is there a better way of doing this ? Thanks a lot.
Because JavaScript uses functional variable scoping.
You want to scope
letterin its own function:Yours is basically a minor variation on the Infamous Loop Problem.
See also closures.
Based on your comments (some of which have been deleted?) I suggest the following approach:
The jQuery
keydownevent executes for every key which the user presses down on – that second argument you’re passing tobinddoesn’t constrain it to only one key.