2012-01-13 47 views
0

我是javascript的新手...请忍受我。修改了w3c教程中的一些jQuery动画代码。我只是试图在for循环中动态地显示本地count(i)变量,该变量代表(4)个jQuery动画调用发生的迭代次数。我期待看到SPAN标签中的文本在每次循环迭代后从0动态变为2。但是,点击按钮时实际发生的是在span标签中立即显示“count:2”,然后发生动画。此代码在以下浏览器中执行(http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_animation):Chrome,IE,FireFox和Safari。我做错了什么,我怎么才能使这个工作?JavaScript/jQuery动画:奇怪的循环行为

<html> 
<head> 
<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function(){ 
    $("button").click(function(){ 
     for(i=0; i<3; i++) 
     { 
     $("div").animate({height:300},"slow"); //jQuery call 1 
     $("div").animate({width:300},"slow"); //jQuery call 2 
     $("div").animate({height:100},"slow"); //jQuery call 3 
     $("div").animate({width:100},"slow"); //jQuery call 4 
     document.getElementById("count").innerHTML="count: "+i; // JavaScript DOM call 
     } 
    }); 
}); 

</script> 
</head> 

<body> 
    <button>Start Animation</button> 
    <br /><br /> 
    <div style="background:#98bf21;height:100px;width:100px;position:relative"> 
     <span id="count"></span> 
    </div> 
</body> 
</html> 

__原帖以上......这条线之下新workking代码 __ _ __

<html> 

<head> 

<script type="text/javascript" src="jquery.js"></script> 

<script type="text/javascript"> 

    var i=0; 

    $("div").animate({height:300},"slow",function(){ document.getElementById  ("count").innerHTML="jQuery Animation 1"; }); 

    $(document).ready(function(){ $("button").click(function(){ myRecursiveFunction(i); }); }); 

    function myRecursiveFunction(i) 
    { 
    document.getElementById("count").innerHTML="count: "+i; 

    $("div").animate({height:300},"slow"); 

    $("div").animate({width:300},"slow"); 

    $("div").animate({height:100},"slow"); 

    $("div").animate({width:100},"slow",function(){ 
    if(i < 10){myRecursiveFunction(++i);} 
    }); 

} 

</script> 

</head> 

<body> 

<button>Start Animation</button> 

<br /><br /> 

<div style="background:#98bf21;height:100px;width:100px;position:relative"> 

    <span id="count"></span> 

</div> 

</body> 

</html> 

回答

0

animate是一个异步调用。

它立即返回,动画发生在后台。

您的整个循环瞬间运行。

+0

我对迟来的答复表示歉意,我依靠这个板上的电子邮件机制进行通知,并没有收到任何消息。由于动画的调用是异步的,所以问题就变成了:如何在所有这些动画调用中保持计数器变量的状态(每次循环迭代4次调用)? – VincentVega 2012-01-17 20:17:23

+0

创建一个采用'i'的函数,执行一次迭代,然后在回调中用'i + 1'调用它自己。 – SLaks 2012-01-17 21:27:52

+0

不知道如何做到这一点......你能举个例子吗? – VincentVega 2012-01-18 21:38:21

0

您可以添加当动画完成的功能将是第四个参数的动画调用,触发一个回调函数: .animate(属性[,时间] [,缓和] [,完整])

$("div").animate({width:100},"slow","linear", function(){ 
    document.getElementById("count").innerHTML="count: "+i; 
})