我有一个svg rect数组:
var rects[];
function drawRect() {
for(var i=0; i<6; i++) {
var rect = document.createElementNS(NS, 'rect');
rect.setAttributeNS(null, 'id', "srect"+i);
rect.setAttributeNS(null, 'x', x);
rect.setAttributeNS(null, 'y', y);
rect.setAttributeNS(null, 'height', '80');
rect.setAttributeNS(null, 'width', '80');
rect.setAttributeNS(null, 'fill', '#000000');
rects.push(rect);
document.getElementById('svgOne').appendChild(rects[i]);
x+=80;
}...skip...
function actionRect() {
var j=0;
//up
$('#'+rects[j].id).animate({y: '50px'}, 1000);
$('#'+rects[j+1].id).animate({y: '50px'}, 1000, function() {
//down
$('#'+rects[j].id).animate({y: '200px'}, 1000);
$('#'+rects[j+1].id).animate({y: '200px'}, 1000, function() {
j=j+1; //j=1
//up
$('#'+rects[j].id).animate({y: '50px'}, 1000);
$('#'+rects[j+1].id).animate({y: '50px'}, 1000, function() {
//down
$('#'+rects[j].id).animate({y: '200px'}, 1000);
$('#'+rects[j+1].id).animate({y: '200px'}, 1000, function() {
j=j+1; //j=2
//up
$('#'+rects[j].id).animate({y: '50px'}, 1000);
$('#'+rects[j+1].id).animate({y: '50px'}, 1000, function() {
//down
$('#'+rects[j].id).animate({y: '200px'}, 1000);
$('#'+rects[j+1].id).animate({y: '200px'}, 1000, function() {
j=j+1; //j=3
//up
$('#'+rects[j].id).animate({y: '50px'}, 1000);
$('#'+rects[j+1].id).animate({y: '50px'}, 1000, function() {
//down
$('#'+rects[j].id).animate({y: '200px'}, 1000);
$('#'+rects[j+1].id).animate({y: '200px'}, 1000, function() {
j=j+1; //j=4
//up
$('#'+rects[j].id).animate({y: '50px'}, 1000);
$('#'+rects[j+1].id).animate({y: '50px'}, 1000, function() {
//down
$('#'+rects[j].id).animate({y: '200px'}, 1000);
$('#'+rects[j+1].id).animate({y: '200px'}, 1000, function() {
});
});
});
});
});
});
});
});
});
});
}此方法移动到数组中的svg矩形。
虽然代码有点脏,但当我尝试了几十次时,这是同时移动成功的两个rects的唯一方法……
但是当我添加这段代码时,它就不工作了。
function actionRect() {
for(var k=0; k<5; k++) {
var j=0;
//up
...same way...我怎么才能重复这个方法5次呢?
发布于 2015-11-13 07:32:33
称其为递归:
function actionRect(repeat, counter){
counter = counter || 0;
if(repeat === counter){
return;
}
....your code
....recall the function in the last callback
$('#'+rects[j+1].id).animate({y: '200px'}, 1000, function() {
actionRect(repeat, counter++)
});
}
actionRect(5)发布于 2015-11-13 08:08:02
您在那里拥有的是一个简单的回调地狱。记住,在任何编程语言中,重复代码都不是一种好的做法。
var j = 0; ///counter
var up = function() {
console.log("foo");
};
var down = function() {
console.log("bar");
};
function actionRect(callback1, callback2) {
for (var i = 0; i < 5; i++) {
callback1();
callback2();
j++; //counter
console.log("counter is at " + j);
}
}
actionRect(up, down);试试这个,看看回调函数是如何工作的。
https://stackoverflow.com/questions/33683242
复制相似问题