javascript: pass local variables to anonymous function
本问题已经有最佳答案,请猛点这里访问。
问题:如何访问
相关:类似的问题,但没有成功:
- 将局部变量传递给加载器匿名处理函数
-
如何通过匿名分配鼠标悬停时传递局部变量
功能? - javascript匿名函数参数传递
- 如何将变量传递给匿名函数
Java解决方案:
将
目标源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //plugin.buttons is collection of button objects for (var i in plugin.buttons) { var button = plugin.buttons[i]; var icon = button.icon; var text = button.text; var shortcut = button.shortcut; var action = button.action; //action is a function ( or method ) if (shortcut != null && shortcut.length > 0) { if ($.isFunction(action)) { console.log(shortcut); //it's valid shortcut //using jQuery hotkey plugin $('div[contenteditable]').bind('keydown', shortcut, function () { console.log(shortcut); //it's undefined action.call(); //it's undefined also return false; }); } } } |
您可以将其作为事件数据传递
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | for (var i in plugin.buttons) { var button = plugin.buttons[i]; var icon = button.icon; var text = button.text; var shortcut = button.shortcut; var action = button.action; //action is a function ( or method ) if (shortcut != null && shortcut.length > 0) { if ($.isFunction(action)) { $('div[contenteditable]').on('keydown', {shortcut : shortcut}, function (e) { console.log(e.data.shortcut); }); } } } |
但在这种情况下,真正的问题是for循环中没有特殊的范围,因此在for循环中定义变量只会在每次迭代时覆盖相同的变量,这就是为什么它在调用事件处理程序时不起作用的原因 以后的时间。
您必须在新范围中锁定变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | for (var key in plugin.buttons) { (function(i) { var button = plugin.buttons[i]; var icon = button.icon; var text = button.text; var shortcut = button.shortcut; var action = button.action; //action is a function ( or method ) if (shortcut != null && shortcut.length > 0) { if ($.isFunction(action)) { console.log(shortcut); //it's valid shortcut //using jQuery hotkey plugin $('div[contenteditable]').bind('keydown', shortcut, function () { console.log(shortcut); //it's undefined action.call(); //it's undefined also return false; }); } } })(key); } |