[英]My code doesn't work within a $(document).ready() function. Can anyone help me understand why?
I'm trying to learn how to create slideshows for a project at work. 我正在尝试学习如何为工作中的项目创建幻灯片。 I'm using Jquery to store the active image in a variable and then using the next() method to append the active class to that image and remove the active class from the previous image.
我正在使用Jquery将活动图像存储在变量中,然后使用next()方法将活动类附加到该图像并从上一个图像中删除活动类。
Now that all works fine when I just have the function running on it's own. 现在,当我自己运行该函数时,一切正常。 The moment I use a document.ready() function however, it doesn't work.
但是,当我使用document.ready()函数时,它不起作用。 I was able to log some messages to the console within it, but for some reason I couldn't run this function.
我能够将一些消息记录到其中的控制台中,但是由于某些原因,我无法运行此功能。 Each time the console tells me that the slideSwitch function hasn't been defined.
每次控制台告诉我未定义slideSwitch函数时。
Can anyone help me understand this? 谁能帮我理解这一点?
Cheers. 干杯。
$(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>
When the slideshow works it basically just times out the images to create the impression of a slideshow, swapping the z-index values a bit like a deck of cards. 幻灯片播放时,它基本上只是使图像超时以产生幻灯片的印象,交换z-index值的方式有点像一副纸牌。
You are passing a string to setInterval
, so it is evaluated in the global scope and your function is scoped to the anonymous function you pass to ready
(so it isn't found). 您正在将字符串传递给
setInterval
,因此它将在全局范围内求值,并且您的函数的作用域为传递给ready
的匿名函数的范围(因此找不到)。
Never pass a string to setInterval
, always pass a function. 永远不要将字符串传递给
setInterval
,永远不要传递函数。
setInterval(slideSwitch, 5000 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.