【问题标题】:Randomly choosing a fixed number of list items?随机选择固定数量的列表项?
【发布时间】:2013-07-09 20:39:44
【问题描述】:

我正在创建一个记忆游戏,用户必须将一张卡片上的单词与其在另一张卡片上的定义相匹配。

目前,我将所有内容都放在一个列表中,并且单词/定义通过相同的类名链接在一起。

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

我的问题是,由于我不想每次都出现相同的单词,我将如何随机选择仅几个不同的类名出现在页面上。

例如,如果我想让上面的代码增加到 50 个,但一次只显示 6 个不同的单词?

我只是以“1”和“one”为例,如果重要的话,我实际上会使用词汇和定义。

【问题讨论】:

  • 您确实意识到您将需要 Javascript 或像 PHP 或 C# 这样的服务器端语言?使用服务器端方法,这是一个微不足道的问题,而 Javascript 只是稍微困难一些。
  • 是的,我愿意。我只是想知道最有效的方法是什么。

标签: html list random


【解决方案1】:

假设您将继续该类命名约定 -

输入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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多