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/