我正在创建一个实用程序方法,它有助于依次使用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'的匿名函数。这似乎是错误的。但你有那里的成分来修复逻辑。您可以立即或在动画结束时执行代码。 –