jQuery选择具有相同类的随机元素 [英] jQuery select random elements with same class

查看:228
本文介绍了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!

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

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