Randomize numbers with jQuery?

前端 未结 6 560
天涯浪人
天涯浪人 2020-12-05 17:44

Is there a simple jQuery way to create numbers randomly showing then a number 1 -6 is choosing after a few seconds? [Like dice]

相关标签:
6条回答
  • 2020-12-05 17:55

    Others have answered the question, but just for the fun of it, here is a visual dice throwing example, using the Math.random javascript method, a background image and some recursive timeouts.

    http://www.jsfiddle.net/zZUgF/3/

    0 讨论(0)
  • 2020-12-05 18:01

    Javascript has a random() available. Take a look at Math.random().

    0 讨论(0)
  • 2020-12-05 18:02

    Coding in Perl, I used the rand() function that generates the number at random and wanted only 1, 2, or 3 to be randomly selected. Due to Perl printing out the number one when doing "1 + " ... so I also did a if else statement that if the number generated zero, run the function again, and it works like a charm.

    printing out the results will always give a random number of either 1, 2, or 3.

    That is just another idea and sure people will say that is newbie stuff but at the same time, I am a newbie but it works. My issue was when printing out my stuff, it kept spitting out that 1 being used to start at 1 and not zero for indexing.

    0 讨论(0)
  • 2020-12-05 18:06

    You don't need jQuery, just use javascript's Math.random function.

    edit: If you want to have a number from 1 to 6 show randomly every second, you can do something like this:

    <span id="number"></span>
    
    <script language="javascript">
      function generate() {
        $('#number').text(Math.floor(Math.random() * 6) + 1);
      }
      setInterval(generate, 1000);
    </script>
    
    0 讨论(0)
  • 2020-12-05 18:09

    This doesn't require jQuery. The JavaScript Math.random function returns a random number between 0 and 1, so if you want a number between 1 and 6, you can do:

    var number = 1 + Math.floor(Math.random() * 6);
    

    Update: (as per comment) If you want to display a random number that changes every so often, you can use setInterval to create a timer:

    setInterval(function() {
      var number = 1 + Math.floor(Math.random() * 6);
      $('#my_div').text(number);
    },
    1000); // every 1 second
    
    0 讨论(0)
  • 2020-12-05 18:16
    function rollDice(){
       return (Math.floor(Math.random()*6)+1);
    }
    
    0 讨论(0)
提交回复
热议问题