【问题标题】:Display X divs randomly out of a possible Y从可能的 Y 中随机显示 X div
【发布时间】:2010-03-23 05:25:06
【问题描述】:

如何随机显示总共 10 个 div 中的 3 个?

这是我迄今为止尝试过的:

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 解决方案,尽管现阶段的任何事情都会有所帮助。

【问题讨论】:

  • 你不是已经有了吗...?您发布的代码?...
  • 每个div中显示的数据是从哪里来的?这 10 行是你从执行 SQL 查询中得到的吗?
  • 没有数据库。就示例而言,唯一的内容是“内容 x”。目前粘贴的代码不起作用,有什么建议吗?
  • javascript 通常不喜欢数字作为 id,使用字符串。 (而且有些客户不喜欢字符串以数字开头。)
  • @kennebec 你建议我叫 div 什么?

标签: php javascript html random


【解决方案1】:

根据对这个问题的回答: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'); 

【讨论】:

  • LOL - 我看到了这个问题的标题,并认为它与我们上周帮助解决的问题相似。打开问题,发现回答这个问题的人是同一个人。 :-)
  • 不得不响应 Randomness 的号召 ;-) 在这个过程中我展示了扩展内置原型的用处 ;)
【解决方案2】:

您可以将可能的 div 内容放在一个数组中,例如 $divs,然后像这样选择三个:

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

for($i = 1; $i $pick
”; }

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

另一种可能的解决方案是使用@987654321@

【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    相关资源
    最近更新 更多