javascript 使用 JQuery 随机显示一个 div 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18476614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:04:06  来源:igfitidea点击:

randomly display a div class using JQuery

javascriptjqueryhtmldom

提问by Alex

I want to randomly display a div class using JQuery. The code is something like:

我想使用 JQuery 随机显示一个 div 类。代码是这样的:

<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>

So if the random method(random result is within 1 to 4) gives 3 as the result, it shows:

因此,如果随机方法(随机结果在 1 到 4 之间)给出 3 作为结果,则显示:

<div class="item">Three</div>

The rest are hidden. Of course, the code can be changed to make it worked. Thanks.

其余的都是隐藏的。当然,可以更改代码以使其工作。谢谢。

回答by 3dgoo

First we get a random int, from zero to the number of items (minus 1). Then we hide all other elements and show just the randomly chosen one.

首先我们得到一个随机整数,从零到项目数(减 1)。然后我们隐藏所有其他元素,只显示随机选择的元素。

var random = Math.floor(Math.random() * jQuery('.item').length);
jQuery('.item').hide().eq(random).show();

Demo

演示

回答by zarazan

var number = Math.floor(Math.random()*3)
var div = $(".item")[number];
div.show();

回答by Karl-André Gagnon

Something like that :

类似的东西:

$('.item').hide().eq(Math.floor(Math.random()*4)).show()

Fiddle : http://jsfiddle.net/PPXmE/

小提琴:http: //jsfiddle.net/PPXmE/

回答by Ozzy

Working example: jsFiddle

工作示例:jsFiddle

js

js

window.onload=function() {
  var E = document.getElementsByClassName("item");
  var m = E.length;
  var n = parseInt(Math.random()*m);
  for (var i=m-1;i>=0;i--) {
      var e = E[i];
      e.style.display='none';
  }
  E[n].style.display='';
}

js.minified

js.minified

window.onload=function(){var E=document.getElementsByClassName("item");var m=E.length;var n=parseInt(Math.random()*m);for(var i=m-1;i>=0;i--){var e=E[i];e.style.display='none';}E[n].style.display='';}

html

html

<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>
<div class="item">Five</div>
<div class="item">Six</div>
<!-- Add as many as you want! //-->

回答by Donovan Botes

Use the setInterval function.

使用 setInterval 函数。

Working example: http://jsfiddle.net/a0c0ntjc/

工作示例:http: //jsfiddle.net/a0c0ntjc/

setInterval(function(){
        var E=document.getElementsByClassName("item");
        var m=E.length;
        var n=parseInt(Math.random()*m);for(var i=m-1;i>=0;i--){
            var e=E[i];e.style.display='none';
        }
        E[n].style.display='';
},3000);