![](/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.