我正在創建一個實用程序方法,它有助於依次使用jQuery淡化元素。正如你在下面的代碼中看到的,我將添加一個額外的類作爲alreadyFadedIn
一個標誌。在方法調用sequentiallyFadeIn(...)
結束時,我想執行cleanUp
,我想要刪除在sequentiallyFadeIn(...)
方法中所選元素中添加的標誌類。如何強制javascript函數同步/順序執行?
<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
沒有被刪除。原因在我看來,cleanUp方法是異步執行的,它與helper()
中sequentiallyFadeIn
方法的主邏輯一起被異步執行。您還可以注意到日誌消息「已執行清理」。甚至在div完成淡入之前即可打印。
如何使cleanUp
調用在sequentiallyFadedIn
方法中的主邏輯完成後執行?有什麼建議麼?上的jsfiddle
代碼:http://jsfiddle.net/BztLx/11/
一旦'nextElementToFadeIn'不再包含任何元素,看起來你必須在'helper'函數內運行回調。 –
您需要在'fadeIn'的完成函數中調用'callBack'函數。 – Barmar
你的代碼立即執行'helper'(它會移除類'alreadyFadedIn'),並且當fadeIn動畫完成時,執行添加類'alreadyFadedIn'的匿名函數。這似乎是錯誤的。但你有那裏的成分來修復邏輯。您可以立即或在動畫結束時執行代碼。 –