jQuery select random elements with same class

前端 未结 3 731
小鲜肉
小鲜肉 2020-12-04 00:40

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 alread

相关标签:
3条回答
  • 2020-12-04 00:56

    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!

    0 讨论(0)
  • 2020-12-04 00:58

    You can select random item by class name using jquery method eq()

    see the example bellow.

    var len = $(".someClass").length;
    var random = Math.floor( Math.random() * len ) + 1;
    $(".someClass").eq(random).css("background-color", "yellow");
    
    0 讨论(0)
  • 2020-12-04 00:59

    Something like this would work (Trigger it by clicking on an element)

    $(".selectElement").on("click", function() {
        var randomElements = $(".selectElement").get().sort(function() {
            return Math.round(Math.random()) - 0.5;
        }).slice(0, 5);
        $(randomElements).css('border', '1px solid red');
    });​
    

    http://jsfiddle.net/rKFfm/

    0 讨论(0)
提交回复
热议问题