Обратный вызов jQuery animate () запоминает только последнюю переменную в цикле

0

Я пишу сценарий, который в основном делает поездку в коробке каждый раз в разные места, и он задает количество циклов. Движение коробки - это просто функция animate(), которая находится в цикле while.

В этом цикле мы также произвольно выбираем координаты, к которым следует перейти и вернуться. После перехода к указанным координатам я вставляю div в это точное местоположение и делаю его красным. Это я делаю в функции обратного вызова.

Возникающая проблема заключается в том, что div добавляется только к последним координатам, к которым идет окно.

var i =0;

while( i<5 ){ //specifying the cycles for the box' movement

var hstandWidth = $("#hstand").width()+27; //getting the current x-coordinates

//array to randomly select x-coordinates from 
var items = Array(hstandWidth-(50)*1, hstandWidth-(50)*2, hstandWidth-(50)*3, hstandWidth-(50)*4, hstandWidth-(50)*5,hstandWidth-(50)*6,hstandWidth-(50)*7,hstandWidth-(50)*8);                                         
//variable with the x-coordinates, which are randomly fetched from the array
var moveLeft = items[Math.floor(Math.random()*items.length)];

//array to randomly select y-coordinates from 
var items2 = Array(30,30*2,30*3,30*4,30*5,30*6,30*7);
//variable with the y-coordinates, which are randomly fetched from the array
var moveTop = items2[Math.floor(Math.random()*items2.length)];

// y-achs movement
$(this).animate({ "top"  : ""+ moveTop  +"px" }, 800);  
// x-achs movement with the callback function which should add the colored div to every position the box has been
$(this).animate({ "left" : ""+ moveLeft +"px" }, 800, function(){

$("<div style='position: absolute; top: "+moveTop+"px; left: "+moveLeft+"px; background: #ffcccc; width: 50px; height: 30px;'></div>").appendTo("#grid");

});                     
//get the box to the initial position
$(this).animate({"left": "0px"}, 800);
$(this).animate({"top" : "0px" }, 800);
//mark cycle passed
i++;
Теги:
jquery-animate
jquery-callback

1 ответ

1

Переменные moveTop и moveLeft изменяются каждый раз через цикл for поэтому, когда анимация завершается через некоторое время, вы видите только значения в конце цикла в moveTop moveLeft завершения анимации. Вы можете замораживать значения каждый раз через цикл с закрытием следующим образом:

var i =0;

while( i<5 ){ //specifying the cycles for the box' movement

    var hstandWidth = $("#hstand").width()+27; //getting the current x-coordinates

    //array to randomly select x-coordinates from 
    var items = Array(hstandWidth-(50)*1, hstandWidth-(50)*2, hstandWidth-(50)*3, hstandWidth-(50)*4, hstandWidth-(50)*5,hstandWidth-(50)*6,hstandWidth-(50)*7,hstandWidth-(50)*8);                                         
    //variable with the x-coordinates, which are randomly fetched from the array
    var moveLeft = items[Math.floor(Math.random()*items.length)];

    //array to randomly select y-coordinates from 
    var items2 = Array(30,30*2,30*3,30*4,30*5,30*6,30*7);
    //variable with the y-coordinates, which are randomly fetched from the array
    var moveTop = items2[Math.floor(Math.random()*items2.length)];

    // y-achs movement
    $(this).animate({ "top"  : ""+ moveTop  +"px" }, 800);  
    // x-achs movement with the callback function which should add the colored div to every position the box has been

    // create closure to capture moveTop and moveLeft values for later callback
    // use different named variables xmoveTop and xmoveLeft to distinguish the
    // closure variable from the outer for loop variable
    (function(obj, xmoveTop, xmoveLeft) {
        $(obj).animate({ "left" : ""+ xmoveLeft +"px" }, 800, function(){

            $("<div style='position: absolute; top: "+xmoveTop+"px; left: "+xmoveLeft+"px; background: #ffcccc; width: 50px; height: 30px;'></div>").appendTo("#grid");

        });
    })(this, moveTop, moveLeft);                     

    //get the box to the initial position
    $(this).animate({"left": "0px"}, 800);
    $(this).animate({"top" : "0px" }, 800);
    //mark cycle passed
    i++;
}
  • 0
    Привет, 10x за ваш ответ, но я не уверен, как реализовать это в моем коде. Кажется, просто копирование не работает: S
  • 0
    @Stamenov - изменение затрагивает только средние 5 строк кода. Если ваш код не работает, то опишите «что» не работает и показывает ли вы ошибки в консоли. Также обратите внимание, что я изменил moveTop на xMoveTop и moveLeft на xmoveLeft внутри замыкания.
Показать ещё 7 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню