我是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>
我對遲來的答覆表示歉意,我依靠這個板上的電子郵件機制進行通知,並沒有收到任何消息。由於動畫的調用是異步的,所以問題就變成了:如何在所有這些動畫調用中保持計數器變量的狀態(每次循環迭代4次調用)? – VincentVega 2012-01-17 20:17:23
創建一個採用'i'的函數,執行一次迭代,然後在回調中用'i + 1'調用它自己。 – SLaks 2012-01-17 21:27:52
不知道如何做到這一點......你能舉個例子嗎? – VincentVega 2012-01-18 21:38:21