jQueryで要素を順番にフェードするのに役立つユーティリティメソッドを作成しています。以下のコードでわかるように、追加のクラスをalreadyFadedIn
フラグとして追加しています。メソッド呼び出しの最後に、メソッド内の選択した要素に追加したフラグ クラスを削除する場所をsequentiallyFadeIn(...)
実行したいと思います。cleanUp
sequentiallyFadeIn(...)
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function sequentialFadeIn(selectorText, speed, display, callBack) {
display = typeof display !== 'undefined' ? display : "block";
function helper() {
nextElementToFadeIn = $(selectorText).not(".alreadyFadedIn").first();
nextElementToFadeIn.fadeIn(speed, function() {
$(this).addClass("alreadyFadedIn");
helper();
}).css("display", display);
}
helper();
callBack(selectorText);
}
sequentialFadeIn(".toBeFaddedIn", "slow", "inline-block",function cleanUp(selectorText1){
$(selectorText1).removeClass("alreadyFadedIn");
console.log("Clean up has been performed.");
console.log("Selector Text: " +selectorText1);
} );
});
</script>
</head>
<body><style media="screen" type="text/css">
.hello {
background-color: blue;
height:50px;
width: 50px;
display: none;
}
</style>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
</body></html>
alreadyFadedIn
inspect 要素を見ていると、クラスが削除されていないことに気付きました。原因は、 cleanUp メソッドが にあるsequentiallyFadeIn
メソッドのメインロジックと一緒に非同期的に実行されることhelper()
です。「クリーンアップが実行されました」というログ メッセージも確認できます。div のフェードインが完了する前でも印刷されます。
メソッドcleanUp
のメイン ロジックの完了後に呼び出しを実行するにはどうすればよいですか? sequentiallyFadedIn
助言がありますか?
jsfiddle のコード: http://jsfiddle.net/BztLx/11/