为什么我的 jQuery 事件在循环时没有正确绑定?
我正在使用 jQuery 热键插件将一些按键绑定到事件。我尝试将其更改为绑定数组上的循环,但它不起作用。
var letters = ["a","b","c"];
for (var x in letters)
{
var letter = letters[x];
$("el").bind('keydown', letter, function() { /*...*/ })
.bind('keyup', letter, function() { /*...*/ });
}
此代码将所有事件绑定到数组中的最后一个字母(“c”),而不绑定到其他事件。有更好的方法吗?多谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为 JavaScript 使用函数变量作用域。
您希望将
letter
范围限制在其自己的函数中:您的函数基本上是 臭名昭著的循环问题。
另请参阅闭包。
根据您的评论(其中一些已被删除?)我建议采用以下方法:
jQuery
keydown
事件针对用户按下的每个键执行 - 您传递给 < 的第二个参数code>bind 并不将其限制为只有一个键。Because JavaScript uses functional variable scoping.
You want to scope
letter
in 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
keydown
event executes for every key which the user presses down on - that second argument you're passing tobind
doesn't constrain it to only one key.在这种情况下,函数体很重要。如果您在函数表达式中引用任何局部变量(
x
、letters
、letter
...),它们会“关闭” “(谷歌闭包了解更多信息)变量,当调用函数表达式来处理事件时,它们将引用分配给字母的最后一个值。例如:有几种方法可以解决这个问题。一种方法是使用自执行函数:
您的代码
var letter = letter[x];
确实不像这样工作,因为 JavaScript 不支持块级作用域,仅功能级别。这意味着在您的代码中,letter
与letters
处于相同的范围(您还应该谷歌变量提升以获取有关此的更多信息)。In this case, the body of the function is important. If you are referencing any of your local variables (
x
,letters
,letter
, ...) in the function expressions, they "close over" (google closures for more info) the variables and, when the function expression is called to handle the events, they will have a reference to the last value assigned to letter. For example:There are a couple of ways to solve this. One method is to use a self-executing function:
Your code,
var letter = letters[x];
does not work like this because JavaScript does not support block level scoping, only function level. This means in your code,letter
is in the same scope asletters
(You should also google variable hoisting for more information about this).