在下面的代码中,我尝试创建多个处理程序函数,这些处理函数必须调用存储在函数数组(“ buttonHandlers”)中的不同函数。此数组是外部范围的一部分:
buttonJson = {};
for (i = 0; i < buttonNames.length; i++) {
customHandler = buttonHandlers[i];
buttonJson[buttonNames[i]] = function() {
customHandler.apply();
$('#msg-dialog-confirm').dialog("close");
$('body').remove('#msg-dialog-confirm');
...
};
}
上面的代码导致处理程序函数调用函数数组的最后一个数组元素(“ buttonHandlers”)。我希望每个处理程序函数仅调用由相关数组索引指定的关联函数。我怎样才能做到这一点?
customHandler
是一个全局变量,您在每次迭代时都将其覆盖,您应该创建一个新的作用域以锁定值
buttonJson = {};
for (i = 0; i < buttonNames.length; i++) {
(function(button) {
buttonJson[button] = function() {
button.apply();
$('#msg-dialog-confirm').dialog("close");
$('body').remove('#msg-dialog-confirm');
...
};
})(buttonHandlers[i]);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句