jQuery选择具有相同类的随机元素
我有类selectElement的元素。当我点击该类的元素,我选择它,并给它另一个类selectedElements,如果它还没有它。
I have elements with class "selectElement". When I click on element with that class, I "select" it, and give it another class "selectedElements", if it doesn't already have it.
我有一个按钮,应该随机选择一定数量(例如10)的元素与类selectElement,并给他们selectedElement类。
But, I have a button that should randomly select certain number (e.g. 10) of elements with class "selectElement" and give them the "selectedElement" class.
此答案 - > http://stackoverflow.com/a/1764629/1011539 ,但每次都返回相同的值。 ..
I tried something like in this answer -> http://stackoverflow.com/a/1764629/1011539, but it returns same values every time...
编辑:解决Jon的帮助。这是其他用户有类似问题的代码:)
Solved with Jon's help. Here is the code for other users with similar problem :)
$("#chooseElementsRand").live("click",function(){
$(".selectedElements").removeClass("selectedElements");
var maxNum = parseInt($(".maxNum").html());
var randomElements = shuffle($(".selectElement")).slice(0,maxNum).addClass("selectedElements");
$(".selectedNum").html(randomElements.length);
if(randomElements.length==maxNum) {
$(".buttonToProceed").removeClass("notShown");
}
});
随机出现在X中,解决方案是 Fisher-Yates shuffle 。 此网页具有Javascript实现(加上理由,加上漂亮的动画,因此请查看):
Whenever you want to pick N elements really at random out of X, the solution is the Fisher-Yates shuffle. This page has a Javascript implementation (plus rationale, plus nice animations, so go have a look):
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
给定shuffle,然后可以随机选择X个元素
Given the shuffle, you can then pick X elements at random with
var items = shuffle($(".selectElement")).slice(0, X);
这里一个工作的小提琴 来玩。
Here's a working fiddle to play with.
脚注:由于你只对一定数量的随机选择感兴趣,所以没有必要无条件将整个输入数组作为 shuffle
;你可以只洗一小部分,然后使用 .slice
来剪掉它并使用它。我把这作为一个练习;注意,你不能错误地抓住* un * shuffle部分!
Footnote: since you are only interested in a certain amount of random picks, there's no need to unconditionally shuffle the whole input array as shuffle
does above; you could shuffle only a small part and then use .slice
to cut it off and work with it. I 'm leaving this as an exercise; be careful that you don't grab the *un*shuffled part by mistake!