You could refactor to use functions declared outside:
function fadeInRed(){
$("#red").fadeIn(4000);
}
function fadeOutBlue(){
$("#blue").fadeOut(4000, fadeInRed);
}
$("#blue").click(fadeOutBlue);
题
I have different effects. I want each one to be executed only when the previous one has finished. The callback function works well when I have 2 or 3 effects. The problem comes when I have a lot of them and each one is quite complex, the code is really difficult to read and follow. Is there any better way to do that? perhaps a more clean and simple way to present the code?
Here is the example to play: 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;
}
解决方案 2
You could refactor to use functions declared outside:
function fadeInRed(){
$("#red").fadeIn(4000);
}
function fadeOutBlue(){
$("#blue").fadeOut(4000, fadeInRed);
}
$("#blue").click(fadeOutBlue);
其他提示
You can use Promises (an alternative approach to asynchronous callbacks), which jQuery implements.
Example:
var blue = $('#blue');
blue.fadeOut(4000);
blue.promise().done(function(){
$("#red").fadeIn(4000);
});
I always use promise http://api.jquery.com/promise/. Using this feature you will be able to properly handle all call flows, whether they are to be successful or not be successful.
$("#blue").click(function() {
$("#blue").fadeOut('slow');
$("#blue").promise().done(function(){
$("#red").fadeIn(4000);
$("#red").promise().done(function(){
$("#green").fadeIn(4000);
});
});
});
Hope it helps you 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;
}