![](/img/trans.png)
[英]Regex doesn't work. What's wrong with my code? Can anyone help me fix this
[英]My code doesn't work within a $(document).ready() function. Can anyone help me understand why?
我正在尝试学习如何为工作中的项目创建幻灯片。 我正在使用Jquery将活动图像存储在变量中,然后使用next()方法将活动类附加到该图像并从上一个图像中删除活动类。
现在,当我自己运行该函数时,一切正常。 但是,当我使用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
,因此它将在全局范围内求值,并且您的函数的作用域为传递给ready
的匿名函数的范围(因此找不到)。
永远不要将字符串传递给setInterval
,永远不要传递函数。
setInterval(slideSwitch, 5000 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.