簡體   English   中英

jQuery用戶定義函數未在if語句中執行

[英]jQuery user-defined function not executing in if statement

我剛開始學習jQuery,所以我對此感到困惑(如果我的問題很明顯,請原諒)。 當用戶加載網站時,我希望屏幕每5秒連續添加方形圖像,直到他們單擊“單擊我!”。 這阻止了它。 如果我在'(function)'前面添加'$',添加圖像的函數runForever會自行工作,但是在我的按鈕單擊函數中,runForever根本不會運行。 我知道它不會運行,因為我在用戶加載頁面時添加了一條警報語句,但是該頁面從未給我該語句。 但是,當我單擊“單擊我!”時,它確實會提醒我。

 $(document).ready(function() { (function runForever() { (".img-box").append("<div class='img-from-other-class'</div>"); setTimeout(runForever, 5000); }); var clicked = false; $("button").click(function() { if (clicked == false) { alert ("beginning repetition"); runForever(); } else { alert ("button clicked"); clicked = true; return; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div class="container"> <div class="row"> <div class="col-6"> <h3>jQuery Practice</h3> </div> <div class="col-6"> <button class="float-right"> Click Me </button> </div> </div> <div class="row"> <div class="col-12"> <div class="img-box"> <div class="img-from-other-class"></div> </div> </div> </div> </div> </body> 

跟隨樣式css

  .img-from-other-class{ width:50px; height:50px; background:red; border-radius:50%; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <body> <button class="stop-btn">STOP</button> <div class="image-box"></div> <script> $(function(){ function run(){ interval = setInterval(function(){ $('.image-box').append('<div class="img-from-other-class"></div>'); }, 5000); } run(); // click for stop append $('.stop-btn').click(function(){ clearInterval(interval); }); }); </script> </body> <html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM