给定一个很长的列表,我如何随机选择 X 元素

given a long list, how can i select x elements randomly?

本文关键字:列表 何随机 元素 选择 一个      更新时间:2023-09-26

Markup:

<ul>
<li>Bla</li>
<li>Ble</li>
...

<li>zla</li>
</ul>

让我们看看这是一个很长的列表,我怎样才能选择 x 个项目,但随机?

-编辑-

不完全重复,我正在尝试选择 x 个项目;

something like:
var i = 0;
$("li:random").each(function(){
    i++; if(i==50) break;
})

下面是如何使用javascript随机函数获得此函数的快速示例:

$(function() {
    var randomItemsNum = 3;
    var totalItems = $('#mylist > li').length;
    for (var index = 0; index < randomItemsNum; index++) {
        var randomIndex = Math.floor((Math.random() * totalItems) + 1);
        var item = $('#mylist > li:nth-child(' + randomIndex + ')');
        if (item.hasClass('selected')) {
            index--;
            continue;
        }
        else {
            item.addClass('selected');
        }
    }
});

它将选定的 CSS 类添加到 3 个随机列表项中。在此处查看工作演示 - http://jsfiddle.net/Pharaon/PPW9J/1/

function selectRandomFromList($list, num){
    var $children = $list.children(),
        len = $children.length,
        a = [],
        o = {},
        r,
        $items = $([]);
    if (!len) { return $items; }
    if (num >= len) { return $children; }
    // Build an array of unique indices
    while (a.length < num) {
        r = Math.floor(Math.random() * len);
        if (!o.hasOwnProperty(r)) {
            o[r] = 1;
            a.push(r);
        }
    }
    // grab the items
    while (num--) {
        $items = $items.add($children.eq(a.pop()));
    }
    return $items;
}

用法示例:

selectRandomFromList($('ul'), 3);

演示:

http://jsfiddle.net/lbstr/d8JgP/

  1. 选择一个介于 1 和列表长度之间的随机数 (r)。
  2. 选取 el# % r == 0 的所有元素。

完成。:)

我认为

你可以这样做:


var list_length = $("ul li").length;
var x; //Assign amount of items
for(var i = 0; i <= x; i++) {
   Math.floor((Math.random()*list_length));
   //Select stuff in here
}
这样做

:-

randomList = 8;
randomElements = jQuery("li").get().sort(function(){ 
  return Math.round(Math.random())-0.5
}).slice(0,randomList);
$(randomElements).addClass("activeLI");​

.CSS

.activeLI {
    color: red;
}​

将随机列表数字 8 更改为 50 或任何数字。

参考现场演示

从jQuery复制:选择随机元素这个答案。