2010-03-23 82 views
0

如何随机显示总共10个中的3个div?随机显示X div可能Y

这是我到目前为止已经试过:

HTML:

<div id="1">Content 1</div> 
<div id="2">Content 2</div> 
<div id="3">Content 3</div> 
<div id="4">Content 4</div> 
<div id="5">Content 5</div> 
<div id="6">Content 6</div> 

的Javascript:

function randomiseDiv() 
{ 
     // Define how many divs we have 
     var divCount = 6; 

     // Get our random ID (based on the total above) 
     var randomId = Math.floor(Math.random()*divCount+1); 

     // Get the div that's been randomly selectted 
     var chosenDiv= document.getElementById(randomId); 

     // If the content is available on the page 
     if (chosenDiv) 
     { 
      // Update the display 
      chosenDiv.style.display = 'block'; 
     } 
} 
window.onload = randomiseDiv; 

我宁愿一个PHP的解决方案,但在这个阶段,任何事情将是有益的。

+0

难道你已经拥有它了吗?您发布的代码?... – 2010-03-23 05:26:50

+0

每个div中显示的数据来自哪里?这10行是从执行SQL查询中得到的吗? – 2010-03-23 05:31:20

+0

没有数据库。为了示例的目的,唯一的内容是“content x”。目前粘贴的代码不工作,有什么建议? – Jordan 2010-03-23 06:03:57

回答

1

基础上anwser这个问题:Generate unique random numbers between 1 and 100,这里是你如何挑选n独特的成员的数组:

// removes n random elements from array this 
// and returns them 
Array.prototype.pick = function(n) { 
    if(!n || !this.length) return []; 
    var i = Math.floor(this.length*Math.random()); 
    return this.splice(i,1).concat(this.pick(n-1)); 
} 

所以,你可以将它应用于挑3周的div出您的收藏和展示他们:

// build the collection of divs with your framework of choice 
// jQuery would be $('div'), Mootools/Prototype $$('div') 
var divs = document.getElementsByTagName('div'); 
// then pick 3 unique random divs and display them 
// each is part of ECMAscript5 and a number of current js frameworks 
divs.pick(3).each(function (div) { 
    div.style.display = "block"; 
}); 
// Prototype shortcut is divs.pick(3).invoke('show'); 
+0

大声笑 - 我看到了这个问题的标题,并认为它与我们上周帮助过的问题类似。打开这个问题,找到了回答这个问题的同一个人。 :-) – belugabob 2010-03-23 10:10:39

+0

必须回应随机性的呼吁;-)在这个过程中,我展示了扩展内置原型的有用性;) – Alsciende 2010-03-23 10:12:39

0

如果你正在寻找一种PHP方式,你可以试试这个假设$ div是一个包含6个元素的数组。

for($i = 1; $i <= 3; $i++) { 
    $div_num = mt_rand(1,6); 
    echo $div[$div_num]; 
} 
1

你可以在一个阵列,比方说,$divs可能DIV内容,挑三是这样的:

$divs = array("Content 1", "Content 2", "Content 3"); 

for($i = 1; $i <= 3; $i++) { 
    shuffle($divs); 
    $pick = array_pop($divs); 
    echo "<div>$pick</div>"; 
} 

您还应该添加某种错误检查,看是否有在数组中至少有3个值。

另一个可能的解决方案是使用array_rand