开发者

Get random block

开发者 https://www.devze.com 2023-02-03 02:08 出处:网络
I have blocks with ID\'s from block1 to block10. Like this: <div id=\"block1\"></div> <div id=\"block2\"></div>

I have blocks with ID's from block1 to block10.

Like this:

<div id="block1"></div>
<div id="block2"></div>
<div id="block3"></div>
<div id="block4"></div>
<div id="block5"></div>开发者_JAVA技巧
<div id="block6"></div>
<div id="block7"></div>
<div id="block8"></div>
<div id="block9"></div>
<div id="block10"></div>

How do I get random block, with id range from 1 to 10?


var randomnumber=Math.floor(Math.random()*10) + 1;
var obj = document.getElementById('block' + randomnumber);

jQuery:

var randomnumber=Math.floor(Math.random()*10) + 1;
var obj = $('#block' + randomnumber);


First get a random number between 1 and 10

var num = Math.floor(Math.random()*11);

Then get the element with the id + num.

var element = document.getElementById('block'+num);


You have to generate a random number using javascript and then just use a jQuery selector like

var randomNumber=Math.floor(Math.random()*11)
var chosenBlock = $('#block'+randomNumber);

Where 11 dictates that the random number will fall between 0-10. To increase the range to, say, 100, simply change 11 to 101 instead.

EDIT: Remember to number your blocks starting in 0.


The first two answers posted are not quite right. They will retrieve numbers from 0 to 10 since they use floor, not 1 to 10.

Random number calculation works like this:

  1. Math.random returns a decimal value ranging from 0 to 1, BUT NEITHER 0 NOR 1.
  2. Multiplying that decimal value by 10 makes it range from about 0.000001 to 9.99999.
  3. Using the Math.floor on the result will remove the decimal so the answer is now between 0 and 9.
  4. Add 1 to the number to offset its range to 1 to 10.

The full code is this:

var randNumber = 1 + Math.floor(Math.random() * 10);
var randId = 'block' + randNumber;

var obj = document.GetElementById(randId);

Now obj holds the div object, and randId is the id of the random div. Or you could have used jQuery on the last line instead:

var obj = $('#' + randId);
0

精彩评论

暂无评论...
验证码 换一张
取 消