从可能的Y中随机显示X div [英] Display X divs randomly out of a possible Y

查看:87
本文介绍了从可能的Y中随机显示X div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我到目前为止所尝试的:



HTML:

 < div id =1>内容1< / div> 
< div id =2>内容2< / div>
< div id =3>内容3< / div>
< div id =4>内容4< / div>
< div id =5>内容5< / div>
< div id =6>内容6< / div>

Javascript:

  function randomiseDiv()
{
//定义我们有多少个div
var divCount = 6;

//获取我们的随机ID(基于以上总数)
var randomId = Math.floor(Math.random()* divCount + 1);

//获取随机选择的div
var chosenDiv = document.getElementById(randomId);

//如果内容在页面上可用
if(chosenDiv)
{
//更新显示
chosenDiv.style.display = '块';
}
}
window.onload = randomiseDiv;

我更喜欢PHP解决方案,尽管在这个阶段任何事情都会有好处。 b $ b

解决方案您可以在数组中包含可能的div内容,比如 $ divs ,以及选择三个像这样:

 $ divs = array(Content 1,Content 2,Content 3); ($ i = 1; $ i <= 3; $ i ++){
shuffle($ divs);

;
$ pick = array_pop($ divs);
echo< div> $ pick< / div>;
}

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

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


How do I randomly display 3 divs out of a possible 10 in total?

This is what I have tried so far:

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;

I would prefer a PHP solution, although anything at this stage would be beneficial.

解决方案

You could have the possible div contents in an array, say, $divs, and pick three like this:

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

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

You should also add some kind of error check to see if there is at least 3 values in the array.

Another possible solution is to use array_rand.

这篇关于从可能的Y中随机显示X div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆