Randomize numbers with jQuery?

前端 未结 6 581
天涯浪人
天涯浪人 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 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
    

提交回复
热议问题