我的代码在 $(document).ready() 函数中不起作用。谁能帮我理解为什么?

My code doesn't work within a $(document).ready() function. Can anyone help me understand why?

我正在尝试学习如何为工作中的项目创建幻灯片。我正在使用 Jquery 将活动图像存储在变量中,然后使用 next() 方法将活动 class 附加到该图像并从上一张图像中删除活动 class .

现在,当我单独使用函数 运行ning 时一切正常。但是,当我使用 document.ready() 函数时,它不起作用。我能够将一些消息记录到其中的控制台,但出于某种原因我无法 运行 此功能。每次控制台都告诉我 slideSwitch 函数还没有定义。

谁能帮我理解一下?

干杯。

$(document).ready(() => {
    function slideSwitch() {
        var $active = $('.active');
        var $next = $active.next();
        $next.addClass('active');
        $active.removeClass('active');
    }
    setInterval( "slideSwitch()", 5000 );
});
#slideshow {
    position: relative;
    height: 400px;  
    width: 600px;
    margin: 15% auto;
}
.slide {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 8;
    height: 100%;
    width: 100%;
}
.active {
    z-index: 10;
}
.lastActive {
    z-index: 9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="slideshow">
  <img class="slide active" src="https://picsum.photos/200/300?image=0" alt="image of toscana, slideshow image 1" />
  <img class="slide" src="https://picsum.photos/200/300?image=1" alt="image of toscana, slideshow image 1" />
  <img class="slide" src="https://picsum.photos/200/300?image=2" alt="image of toscana, slideshow image 1" />
  <img class="slide" src="https://picsum.photos/200/300?image=3" alt="image of toscana, slideshow image 1" />
</div>

当幻灯片放映时,它基本上只是让图像超时以创建幻灯片放映的印象,有点像一副纸牌交换 z-index 值。

您正在将 字符串 传递给 setInterval,因此它在 global 范围内进行评估并且您的函数在范围内传递给 ready 的匿名函数(因此找不到)。

从不 将字符串传递给 setInterval,总是传递函数。

setInterval(slideSwitch, 5000 );