私はjavascriptの初心者です...私と一緒にご負担ください。 w3cチュートリアルからいくつかのjQueryアニメーションコードを修正しました。私は、(4)jQueryアニメーション呼び出しのために行われた反復の数を表すforループ内のローカルcount(i)変数を動的に表示しようとしています。私はSPANタグのテキストが各ループの繰り返しの後に0から2に動的に変化することを期待していました。しかし、ボタンをクリックしたときに実際に起こることは、spanタグに "count:2"が直ちに現れ、アニメーションが行われることです。このコードは、Chrome、IE、FireFox、およびSafariの各ブラウザで同じ(http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_animation)を実行します。私は間違って何をしているのですか?これをどのように機能させることができますか?JavaScript/jQuery animation:奇妙なループの振る舞い
<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
'i'をとり、1回の反復を行い、次にコールバックで' i + 1'を使って自分自身を呼び出す関数を作成します。 – SLaks
これを行う方法がわかりません...例を教えてください。 – VincentVega