使用jQuery显示随机div [英] Showing random divs using Jquery

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

问题描述

如果包含图像的div,我有一个列表.每次页面加载时,我需要随机显示其中的4个.这是我开始的代码.

I have a list if divs which contain images. I need to randomly show 4 of these each time the page loads. Here's the code I'm starting with.

<div class="Image"><img src="/image1.jpg"></div>
<div class="Image"><img src="/image2.jpg"></div>
<div class="Image"><img src="/image3.jpg"></div>
<div class="Image"><img src="/image4.jpg"></div>
<div class="Image"><img src="/image5.jpg"></div>
<div class="Image"><img src="/image6.jpg"></div>
<div class="Image"><img src="/image7.jpg"></div>

所有这些都将以display:none开始,我想随机抽取4个div并将它们设置为display:block.我假设我需要在某处使用"Math.random()",但不确定JQuery如何做到这一点.任何指针将不胜感激.

All of these will start as display:none, I'd like to take 4 of the divs at random and set them to display:block. I'm assuming I need to use "Math.random()" in there somewhere but not sure how JQuery does this. Any pointers would be appreciated.

推荐答案

我发现对它们进行随机排序,然后显示前4个最简单,例如:

I find sorting them randomly then showing the first 4 to be the easiest, like this:

var divs = $("div.Image").get().sort(function(){ 
            return Math.round(Math.random())-0.5; //so we get the right +/- combo
           }).slice(0,4);
$(divs).show();

您可以在此处进行测试.如果您还希望对顺序进行随机化(不仅限于显示的顺序),那么您已经对它们进行了排序,因此只需更改以下内容,即可按新顺序将它们附加到同一父项中:

You can test it out here. If you want to also randomize the order (not just which are shown), you already have them sorted so just append them to the same parent in their new order by changing this:

$(divs).show();
//to this:
$(divs).appendTo(divs[0].parentNode).show();

您可以在此处测试该版本.

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

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