2013-07-09 43 views
0

我正在創建一個記憶遊戲,用戶必須將一張卡上的單詞與另一張卡上的單詞相匹配。隨機選擇固定數量的列表項目?

目前,我有一個列表中的所有內容,並且/ defintion這個詞通過相同的類名連接在一起。

<li class="match1"> 1 </li> 
<li class="match2"> Two </li> 
<li class="match1"> One </li> 
<li class="match2"> 2 </li> 

我的問題是,因爲我不希望有相同的詞出現在每一次,我將如何去隨機選擇只有幾個不同的類名出現在頁面上,進行更多的。

例如,如果我想讓上面的代碼達到50,但一次只顯示6個不同的單詞?

我只是使用「1」和「one」作爲例子,我實際上會使用詞彙和定義,如果它很重要的話。

+1

你一定要明白你要需要JavaScript還是像PHP或C#這樣的服務器端語言?使用服務器端的方法,這是一個微不足道的問題,只有Javascript稍微難一些。 –

+0

是的,我願意。我只是想知道做這件事最有效的方法是什麼。 – Rygh2014

回答

0

假設你繼續這個類的命名約定 -

把一個li { display: none; }預先隱藏所有的選項,然後:

//Set these as you wish 
var totalOptions = 50, showOptions = 6, random; 

//Loop this code as many times as the value of showOptions 
for (var i = 0; i < showOptions; i++) { 

    //Generate a random number between 1 and the value of totalOptions 
    do { 
     random = 1 + Math.floor(Math.random()*totalOptions); 
    } 
    //Loop while the chosen value is something already shown 
    while (document.getElementsByClassName('match' + random)[0].style.display == 'list-item'); 

    //Hide word && definition by class name 
    document.getElementsByClassName('match' + random)[0].style.display = 'list-item'; 
    document.getElementsByClassName('match' + random)[1].style.display = 'list-item'; 

} 

Fiddle