Javascript jquery:数组丢失了回调函数

问题描述 投票:0回答:1

我有这个代码只能用我的数组的最后一个元素做我想要的...为什么会这样?

    $(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)

            });

        }
    });
javascript jquery arrays callback
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.