You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery使用fadeIn/fadeOut轮播数组文本到第N项不显示报错如何解决

问题原因

你的代码存在2个核心错误:

  • animate函数在fadeIn回调中被调用时,没有传入text数组参数,导致第二次执行animate时形参text为undefined,访问text.length直接抛出Uncaught TypeError错误
  • index变量定义在animate函数内部,每次调用animate都会被重置为0,就算解决传参问题,也只会永远切换到索引1对应的文本2,无法展示第三项

修复方案

把index变量移到函数外部避免每次重置,调用animate回调时主动传入text参数即可,修复后代码如下:

JS代码

// index移到函数外部,避免每次执行animate被重置
var index = 0;
function animate(text){
    $(".text").delay(5000).fadeOut(1000, function(){
        index = (index + 1) % text.length;
        this.textContent = text[index];
    // 回调调用animate时主动传入text参数
    }).fadeIn(1000, function() {
        animate(text)
    });
}
var text = ['1', '2', '3'];
$(".text").text(text[0]);
animate(text);

HTML代码

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

内容的提问来源于stack exchange,提问作者HiDayurie Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:06:02