2010-03-23 164 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