我有不同的效果。我希望每个人只有在前一个完成后才能执行。当我有2或3个效果时,回调函数效果很好。当我有很多这些问题并且每一个都非常复杂时,问题就出现了,代码很难阅读和遵循。有没有更好的方法呢?或许是一种更简洁的方式来呈现代码?
以下是播放的示例:http://jsfiddle.net/83xrg/
JQUERY:
$("#blue").click(function() {
$("#blue").fadeOut(4000, function() {
$("#red").fadeIn(4000);
});
});
HTML:
<div id="blue"></div>
<div id="red"></div>
CSS:
#blue{
position: absolute;
top: 150px; left: 150px;
width:200px; height:200px;
background-color:blue;
cursor:pointer;
}
#red{
position: absolute;
top:150px; left:150px;
width:200px; height: 200px;
background-color:red;
display:none;
}
答案 0 :(得分:2)
您可以使用Promises(异步回调的替代方法),jQuery implements。
示例:
var blue = $('#blue');
blue.fadeOut(4000);
blue.promise().done(function(){
$("#red").fadeIn(4000);
});
答案 1 :(得分:1)
你可以重构使用在外面声明的函数:
function fadeInRed(){
$("#red").fadeIn(4000);
}
function fadeOutBlue(){
$("#blue").fadeOut(4000, fadeInRed);
}
$("#blue").click(fadeOutBlue);
答案 2 :(得分:1)
我总是使用承诺http://api.jquery.com/promise/。 使用此功能,您将能够正确处理所有呼叫流程,无论它们是成功还是不成功。
$("#blue").click(function() {
$("#blue").fadeOut('slow');
$("#blue").promise().done(function(){
$("#red").fadeIn(4000);
$("#red").promise().done(function(){
$("#green").fadeIn(4000);
});
});
});
希望它可以帮助你http://jsfiddle.net/7wv6H/1/
HTML
<div id="blue"></div>
<div id="red"></div>
<div id="green"></div>
CSS
#blue{
position: absolute;
top: 150px; left: 150px;
width:200px; height:200px;
background-color:blue;
cursor:pointer;
}
#red{
position: absolute;
top:150px; left:150px;
width:200px; height: 200px;
background-color:red;
display:none;
}
#green{
position: absolute;
top:150px; left:150px;
width:200px; height: 200px;
background-color:green;
display:none;
}