简体   繁体   中英

jQuery user-defined function not executing in if statement

I am new to learning jQuery so I've been stumped with this for a while (and excuse me if my question is very obvious). When the user loads the site, I want the screen to append square images continuously every 5 seconds, until they click "Click Me!" which stops it. The function runForever which appends the images works on it's own if I add '$' in front of '(function)', but inside my button click function, runForever doesn't run at all. I know it doesn't run because I added an alert statement for when the user loads the page, but the page never gives me this statement. It does, however, give me the alert for when I click 'Click Me!'.

 $(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> 

style css in follow

  .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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM