jQuery用户定义函数未在if语句中执行

时间:2018-06-30 17:48:25

标签: javascript jquery function click

我对学习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>

1 个答案:

答案 0 :(得分:0)

跟随样式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>