最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get random block - Stack Overflow

programmeradmin1浏览0评论

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>
<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?

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>
<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?

Share Improve this question asked Jan 6, 2011 at 17:01 JamesJames 43.7k54 gold badges137 silver badges163 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7
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)

  1. 暂无评论