画面上を移動するためのいくつかのボックスを含む簡単な例があります。各ボックスは、前のボックスが完了するまで移動しないでください。を使用した実用的なソリューション.shift()
がありますが、forループとを使用してこれを繰り返すことができるはず$.each
です。誰もがのためにそして$.each
働く方法を知っていますか?
ここをいじると、Shiftボタンは私が望むように機能します。
ありがとう。
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;
}