在 Javascript 中生成不同回调函数的数组
我正在尝试生成一组回调函数以在 jQuery UI 对话框中使用
给定以下代码:
for(var x in methods)
{
buttons[x] = function() {
var method = methods[x];
var data = $('#dialog_'+model+' form').serialize();
data += '&form='+model;
$.post(
$('#dialog_'+model+' form').attr('action')+'method/'+method+'/',
data,
function(r) {
handleFormReturn(r);
},
'json'
);
};
}
调用时,该函数显然将使用变量 x 的最后一个已知值,而不是我需要的值。如何避免此问题而不必求助于使用 eval() ?
也许我的做法是错误的,但据我所知,不可能将参数传递给回调。
I'm trying to generate an array of callback functions for use in a jQuery UI dialog
Given the following code:
for(var x in methods)
{
buttons[x] = function() {
var method = methods[x];
var data = $('#dialog_'+model+' form').serialize();
data += '&form='+model;
$.post(
$('#dialog_'+model+' form').attr('action')+'method/'+method+'/',
data,
function(r) {
handleFormReturn(r);
},
'json'
);
};
}
When called, the function will obviously use the last known value of the variable x and not the one that I need. How can I avoid this problem without having to resort to using eval() ?
Maybe I'm going about this all wrong but as far as I know it's not possible to pass a parameter to the callback.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在
for
循环中的每次传递期间创建一个新的变量作用域。这只能通过调用函数来完成。现在,
buttons[x]
函数引用的x
值将是传递给createButton
的值。You need to create a new variable scope during each pass in the
for
loop. This can only be done by invoking a function.Now the value of
x
that thebuttons[x]
function refers to will be the one that was passed tocreateButton
.patrick dw 解决方案的即时函数版本:
An immediate function version of patrick dw's solution:
您需要为方法数组中的每个元素创建一个闭包:
You need to create a closure for each element in methods array: