【发布时间】:2011-02-26 13:52:41
【问题描述】:
在 each 迭代器之后调用回调函数时遇到困难。
这是一个例子:
<html>
<head>
<script type="text/javascript" src="jquery-1.4.min.js"></script>
<script type="text/javascript" src="move.js"></script>
</head>
<body>
<div>
<div class="ani" style="position:relative; display: inline-block; top:10px; left:0px; width:30px; height:30px; background:#ddd;"></div>
<div class="ani" style="position:relative; display: inline-block; top:10px; left:110px; width:30px; height:30px; background:#ddd;"></div>
<div class="ani" style="position:relative; display: inline-block; top:10px; left:210px; width:30px; height:30px; background:#ddd;"></div>
<div class="ani" style="position:relative; display: inline-block; top:10px; left:310px; width:30px; height:30px; background:#ddd;"></div>
</div>
</body>
</html>
$(document).ready(function(){
$ani = $('div.ani');
var redFlash = function(){
$ani.eq(0).css('background-color','#e35');
};
var goingDown = function(){
$ani.each(function(i){
$(this).animate({'top':'100px'}, (i+1)*2000);
}),redFlash()};
goingDown();
});
redFlash 函数并没有被调用。我也试过:
var goingDown = function(){
$ani.each(function(i){
$(this).animate({'top':'100px'}, (i+1)*2000);
}),function(){
$ani.eq(0).css('background-color','#e35');
};
};
无济于事。
each 迭代器内的所有动画 完成后如何让redFlash 运行?有没有办法在动画完成后让 goingDown 回调到 redFlash?
另外,有没有人知道关于 javascript/jquery 回调函数的任何好的在线资源或书籍?我手上的书在这个主题上有点片面。
编辑:在使用计数器时使用 Pointy 的指针解决。
$(document).ready(function(){
$ani = $('div.ani');
var redFlash = function(){
$ani.eq(0).css('background-color','#e35');
};
var ani_size = $ani.length-1;
console.debug(ani_size);
var goingDown = function(){
$ani.each(function(i){
$(this).animate({'top':'100px'}, (i+1)*2000, function(){
console.debug(i);
if (i == ani_size){
redFlash();
}
});
});
};
goingDown();
});
【问题讨论】:
-
redFlash()调用前面是逗号而不是分号的任何特殊原因? -
当您在问题中输入“pyquery”时,您的意思是“jQuery”,对吧?
-
我在那儿放了一个逗号,因为我认为这就是回调函数的调用方式。
-
回调不是通过在函数调用前放置逗号来定义的。通常,当您看到前面有逗号的回调时,这是因为您将函数作为参数传递给另一个函数的调用。
someFunc( "someArg", callbackFunction )需要编写一个函数来处理回调函数作为参数。它不仅仅是自动的。 -
@patrick 好的,显然 each() 不能以这种方式工作。那么如何将回调合并到 goDown() 中?
标签: javascript jquery callback jquery-animate each