Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

jQuery select random elements with same class

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.

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.

I tried something like in this answer -> https://stackoverflow.com/a/1764629/1011539, but it returns same values every time...

EDIT: 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");
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

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.

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...