在JS中需要有关循环的帮助

时间:2010-03-21 23:40:34

标签: javascript ajax prototypejs scriptaculous

我有这样的功能,它添加了一个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框架。

2 个答案:

答案 0 :(得分:1)

问题在于你对闭包的理解。在封闭函数中作为局部变量的周,日等的值将是AddClassroomDrops执行完成时的最后一个值。避免这种情况的典型方法是返回一个函数并将局部变量传递给另一个函数。例如:

function enclosing()
{
   for(var i = 0; i < 10; i++)
   {
       var f = function(j) { return function closureFunc() { // use j here }; }(i);
       // here you can do Droppables.add(f);
   }
}

答案 1 :(得分:0)

这是在萨满舞蹈之后起作用的:

function AddClassroomDrops(grid, weeks, days, times) {
    for(week = 1; week <= weeks; week++) {
        for (day = 1; day <= days; day++) {
            for (time = 1; time <= times; time++ ) {
                var drop = function(week, day, 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
                                }
                              }
                            );
                          }
                    });
                 }
              drop(week, day, time);
            }
        }
    }
}