-->

setInterval with jQuery.html only updates once?

2019-08-11 19:41发布

问题:

<?php
  echo '
    <script type="text/javascript">
      $(function() {
        var refresh = setInterval(function() {
          $("#content").html("'.rand().'");
        }, 3000);
      });
    </script>

    <div id="content"></div>
  ';
?>

This will update the div "content" with a random number after 3 seconds, however it only updates once. Why does it not continually generate a new number every three seconds, and how can I make it do precisely that?

Thank you in advance for any assistance rendered.

回答1:

Ha. PHP is run on the SERVER side. JS is on the client.

you need to generate the rand on the JS side not he php side...

js code:

<script type="text/javascript">
  $(function() {
    var refresh = setInterval(function() {
      var randomnumber = Math.floor(Math.random()*11);
      //where 11 dictates that the random number will fall between 0-10
      $("#content").html(randomnumber);
    }, 3000);
  });
</script>

<div id="content"></div>