Ale*_*exC 24 javascript jquery
如何选择前5个随机元素
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
...
<li>N</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
alert($("li:random").text());
Run Code Online (Sandbox Code Playgroud)
但它需要所有随机元素.我只想要前5个.
还有另一种方法可以做同样的事情吗?
duc*_*lip 52
这里是如何从jQuery选择中获取5个随机元素,不需要插件!
randomElements = jQuery("li").get().sort(function(){
return Math.round(Math.random())-0.5
}).slice(0,5)
Run Code Online (Sandbox Code Playgroud)
此时,您有5个DomElements已经从jQuery返回的所有LI中随机选择
然后你可以随心所欲地做任何事情,
例如改变它们的颜色:
$(randomElements).css("color","red")
Run Code Online (Sandbox Code Playgroud)
或显示其组合文本内容:
$(randomElements).text()
Run Code Online (Sandbox Code Playgroud)
获取随机数索引1-5,并使用该索引获取ul的子项.像这样:
var index = Math.floor(Math.random() * 5) + 1; // nth-child indices start at 1
alert($("ul:nth-child(" + index + ")").text());
Run Code Online (Sandbox Code Playgroud)
使用Fisher-Yates shuffle我为此创建了一个小脚本.这是通过首先创建jQuery元素数组的随机混乱和切片副本,然后过滤掉两个数组中不存在的所有元素来完成的.
您可以在http://www.afekenholm.se/jquery-rand上阅读相关内容.这是脚本:
/**
* jQuery.rand v1.0
*
* Randomly filters any number of elements from a jQuery set.
*
* MIT License: @link http://www.afekenholm.se/license.txt
*
* @author: Alexander Wallin (http://www.afekenholm.se)
* @version: 1.0
* @url: http://www.afekenholm.se/jquery-rand
*/
(function($){
$.fn.rand = function(k){
var b = this,
n = b.size(),
k = k ? parseInt(k) : 1;
// Special cases
if (k > n) return b.pushStack(b);
else if (k == 1) return b.filter(":eq(" + Math.floor(Math.random()*n) + ")");
// Create a randomized copy of the set of elements,
// using Fisher-Yates sorting
r = b.get();
for (var i = 0; i < n - 1; i++) {
var swap = Math.floor(Math.random() * (n - i)) + i;
r[swap] = r.splice(i, 1, r[swap])[0];
}
r = r.slice(0, k);
// Finally, filter jQuery stack
return b.filter(function(i){
return $.inArray(b.get(i), r) > -1;
});
};
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22506 次 |
| 最近记录: |