需要有关 JS 循环的帮助
我有这样的函数,它添加了一个 droppables 网格:
function AddClassroomDrops(grid, weeks, days, times) {
for(week = 1; week <= weeks; week++) {
for (day = 1; day <= days; day++) {
for (time = 1; time <= times; time++ ) {
Droppables.add('container_grid'+ grid + '_week' + week + '_day' + day + '_time' + time, {
accept: 'pair',
hoverclass : 'hovered_receiver',
onDrop: function(pair, receiver) {
new Ajax.Request(
'/pairs/'+pair.id+'/update_on_drop', {
method : 'put',
parameters : {
classroom : grid,
week : week,
day : day,
time : time,
container : receiver.id
}
}
);
}
});
}
}
}
}
问题是 Ajax.Request 的参数(周,日,时间)始终等于周 + 1,次 + 1,天 + 1。但它们必须根据循环。哦,是的 - Droppables 来自 script.aculo.us 框架。
I have such function, that adds a grid of droppables:
function AddClassroomDrops(grid, weeks, days, times) {
for(week = 1; week <= weeks; week++) {
for (day = 1; day <= days; day++) {
for (time = 1; time <= times; time++ ) {
Droppables.add('container_grid'+ grid + '_week' + week + '_day' + day + '_time' + time, {
accept: 'pair',
hoverclass : 'hovered_receiver',
onDrop: function(pair, receiver) {
new Ajax.Request(
'/pairs/'+pair.id+'/update_on_drop', {
method : 'put',
parameters : {
classroom : grid,
week : week,
day : day,
time : time,
container : receiver.id
}
}
);
}
});
}
}
}
}
The problem is that params of Ajax.Request (week, day, time) are always equal to weeks + 1, times + 1, days + 1. But they must vary according to the cycle. Oh, yes - Droppables is from script.aculo.us framework.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题出在你对闭包的理解上。封闭函数中的局部变量周、日等的值将是 AddClassroomDrops 执行完成时的最后一个值。避免这种情况的典型方法是返回一个函数并将局部变量传递给另一个函数。例如:
The problem is with your understanding of closures. The value of week, day, etc. which are local variables in the enclosing function will be the last value at the time of AddClassroomDrops' completion of execution. The typical way to avoid this is returning a function and passing the local variable to yet another function. For example:
这在萨满舞蹈之后起作用:
This works after shaman dances: