我有这段代码只对数组的最后一个元素做我想要的...为什么是这样?
$(document).ready(function () {
var miArray=["Diseño web multidioma","Desarrollo de aplicaciones","Programacion servidores"];
for (i = 0; i <3; i++) {
$("#animation").hide().text(miArray[i]).fadeIn(2000, function () {
//$(this).css({"background-color": "yellow"}, function(){
//var div = $("#anuncio");
alert("the value of miArray[i] is: " + miArray[i]);
$(this).css({"background-color": "yellow"});
$(this).animate({height: '160px', opacity: '0.8'}, "slow");
$(this).animate({width: '300px', opacity: '0.8',}, "slow");
$(this).animate({height: '160px', opacity: '0.8'}, "slow");
/* /!*$(this).animate({width: '100px',opacity: '0.8' }, "slow");*!/*/
$(this).fadeOut(2000)
});
}
});
答案 0 :(得分:0)
.fadeIn()
和.animation()
是异步过程,其中for
循环不等待其完成,请参见JavaScript closure inside loops – simple practical example。您可以使用$.map()
,.queue()
,.dequeue()
,.promise()
和.then()
代替for
循环,以等待一个或多个异步任务的完成在执行queueName
数组中的下一个函数之前。
$(document).ready(function() {
var miArray = ["Diseño web multidioma", "Desarrollo de aplicaciones", "Programacion servidores"];
$("#animation")
.queue("animation"
, $.map(miArray, function(value) {
// `next` is the next function in `queue` named `"animation"`
return function(next) {
return $("#animation")
.hide()
.text(value)
.fadeIn(2000, function() {
$(this).css({
"background-color": "yellow"
})
.animate({
height: '160px',
opacity: '0.8'
}, "slow")
.promise()
.then(function() {
return $(this).animate({
width: '300px',
opacity: '0.8',
}, "slow").promise()
})
.then(function() {
return $(this).animate({
height: '160px',
opacity: '0.8'
}, "slow").promise()
})
.then(function() {
// call `next` function in `"animation"` queue at `.fadeOut()` callback
$(this).fadeOut(2000, next)
})
})
}
}))
.dequeue("animation")
.promise("animation")
.then(function() {
console.log("done")
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<div id="animation"></div>