2012-11-25 2 views
1

간단한 예제를 통해 여러 상자로 화면을 이동할 수 있습니다. 각 상자는 이전 상자가 완료 될 때까지 움직여서는 안됩니다. .shift()을 사용하는 작업 솔루션이 있지만 for 루프와 $.each을 사용하여 반복 할 수 있어야합니다. 누구든지에 대한을 얻으려면 $.each 일하는 방법을 알고 계십니까?Javascript 및 jQuery : 배열을 반복하지만 애니메이션이 완료 될 때까지 기다림

fiddle here 시프트 버튼은 내가 원하는대로 작동합니다.

감사합니다.

JS :

boxes = [ 
    ['.box0', 'animate', [ {left: '200px' }, 1000 ] ], 
    ['.box1', 'animate', [ {left: '200px' }, 1000 ] ], 
    ['.box2', 'animate', [ {left: '200px' }, 1000 ] ], 
    ['.box3', 'animate', [ {left: '200px' }, 1000 ] ], 
    ['.box4', 'animate', [ {left: '200px' }, 1000 ] ], 
    ['div', 'animate', [ {left: '0px' }, 1000 ] ] 
]; 
$('.eachMethod').click(animEach); 
$('.ifMethod').click(animFor); 
$('.shiftMethod').click(animShift); 
function animEach(){ 
    $.each(boxes, function(){ 
    $.fn[this[1]].apply($(this[0]), this[2]).promise().done(); 
    }); 
}; 
function animFor(){ 
    for (i=0; i < boxes.length; i++) { 
    b=boxes[i]; 
    $.fn[b[1]].apply($(b[0]), b[2]).promise().done(); 
    } 
}; 
function animShift(){ 
    b = boxes.shift(); 
    if (b) { 
    $.fn[b[1]].apply($(b[0]), b[2]).promise().done(animShift); 
    } 
};​ 

HTML :

<ul> 
    <li><button class='eachMethod'>$.each</button></li> 
    <li><button class='ifMethod'>if</button></li> 
    <li><button class='shiftMethod'>shift</button></li> 
</ul> 
<div class='box0'></div> 
<div class='box1'></div> 
<div class='box2'></div> 
<div class='box3'></div> 
<div class='box4'></div>​ 

CSS :

div{ 
clear: both; 
background-color: green; 
width: 40px; 
height: 40px; 
Position: relative;  
} 
ul li { 
    float: left; 
} 

답변

1

animate() 비동기이므로, 루프는 각 요소에 애니메이션을 호출 몇 밀리 초에 완료됩니다 사실상 동시에. .promise().done()은 루프를 사용할 때 아무 것도하지 않습니다.

animShift()은 한 번에 하나 개의 요소에 애니메이션을 적용하고, 다음 호출이 done() 내에 이후 처음 애니메이션이 도움을

+0

감사 완료 될 때까지 발생하지 않습니다 사용 버전; .promise()가 없으면 다음 애니메이션이 실행되지 않습니다. – twinturbotom

관련 문제