选择5个随机元素 [英] Select 5 random elements

查看:114
本文介绍了选择5个随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何选择前5个随机元素

How can I select the first 5 random elements

<ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
     ...
    <li>N</li>
</ul>

我正在使用这个插件

alert($("li:random").text());

但它需要所有随机元素。我只想要前5个。

but it takes all random elements. I only want the first 5.

还有另外一种方法可以做同样的事情吗?

Is there another way to do the same thing?

推荐答案

以下是如何从jQuery选择中获取5个随机元素,不需要插件!

Here's how to get 5 random elements from a jQuery selection, no need of plugins!

randomElements = jQuery("li").get().sort(function(){ 
  return Math.round(Math.random())-0.5
}).slice(0,5)

此时你有5个DomElements是从jQuery返回的所有LI中随机选择的

At this point you have 5 DomElements that have been selected randomly from all the LIs that jQuery returned

然后你可以用它们做任何你喜欢的事情,

例如改变它们的颜色:

You can then do whatever you like with them,
e.g change their color:

$(randomElements).css("color","red")

或显示其组合文本内容:

or display their combined text contents:

$(randomElements).text()

这篇关于选择5个随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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