首页 > 解决方案 > Javascript/jQuery fadeIn fadeOut 在 N 长度后不显示

问题描述

我正在使用 Javascript/jQueryfadeIn delayfadeOut我的数组文本。

function animate(text){
    var index = 0;
    $(".text").delay(5000).fadeOut(1000, function(){
        index = (index + 1) % text.length;
        this.textContent = text[index];
    }).fadeIn(1000, animate);
}

var text = ['1', '2', '3'];

$(".text").text(text[0]); //First Show

animate(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text"></div>

上面的代码只在2. 3 从不显示这样的错误Uncaught TypeError: Cannot read property 'length' of undefined

上面的代码有没有遗漏的部分?

标签: javascriptjquery

解决方案


animate接受一个参数,您最初将其作为数组传入:

animate(text);

但是递归回调没有得到参数:

}).fadeIn(1000, animate);

index也没有递归地坚持。

我将摆脱参数并使用外部变量来代替textindex

var index = 0;

function animate() {
  $(".text").delay(1000).fadeOut(1000, function() {
    index = (index + 1) % text.length;
    this.textContent = text[index];
  }).fadeIn(1000, animate);
}

var text = ['1', '2', '3'];

$(".text").text(text[0]); //First Show

animate(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text"></div>


推荐阅读