Randomize the divs that I append into another one

2019-06-05 03:07发布

问题:

This is what I have:

$(function(){
    $('.apple').appendTo('.container');
});

Now, lets say I have 20 different divs with class name .apple.

How can I have them append into Container randomly? So every time that I load the page the order would be different.

Thank you in advance!

回答1:

$.when($(".apples"), [])
    .done(function (data, apples) {
    $.each(data, function (k, v) {
        setTimeout(function () {
            apples.push(v);
            if (apples.length === data.length) {
                $(apples).appendTo(".container")
            };
        }, 1 + Math.floor(Math.random() * 5));
    });
});

jsfiddle http://jsfiddle.net/guest271314/d4p39/



回答2:

You can try below code by getting some random value and use it for if / else conditions :

$(function(){
    $('.apple').each(function(){
       var random = ((Math.random()*100) + 50).toFixed();

       if(random > 100)
          $('.container').append($(this)); 
       else if(random < 100)
           $('.container').prepend($(this)); 
        else
        {
          var childCount = $('.container').children().length;
            $('.container').find('div:eq('+(childCount/2)+')').append($(this));   
        }
    });
});

Demo



回答3:

Use like this:

var idx;
$('.apple').each(function(){
   idx = Math.floor(Math.random() * 20) +1;
   $(this).eq(idx).appendTo('.container');
});


回答4:

Giving you an approach which can be used for any number of elements.

Generate random numbers between 0 and 1 and based on it, either append or prepend your element

$('.apple').each(function(){
   var j = Math.floor(Math.random() * 2);
   if(j== 0)
       $('.container').append($(this)); 
   else 
       $('.container').prepend($(this)); 
});


回答5:

You may also use like this:

$('.apple').sort(function(a,b){
  var tmp = parseInt( Math.random()*20 );
  var isOE = tmp % 2;
  var isPN = tmp > 10 ? 1 : -1;
  return( isOE * isPN );
}).appendTo('.container');

for more details view this



回答6:

EDITED

You can do something like this:

//create an array equals number of .apple
var arr = [];

$(".apple").each(function(index){
    arr.push(index);//create an array with index
});

var shuffled_array = shuffle(arr);//shuffle the array

shuffled_array.forEach(function(index) {
    $(".apple:eq("+index+")").appendTo('.container');
});

function shuffle(array) { //Fisher–Yates Shuffle function
  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;
}


回答7:

Try Something like this:

HTML Code :

<div class="wrapper"><div class="apple">Apple</div></div>
<button id="test">Add</button>
<div class="container"></div>

js code :

  $('#test').click(function(){
    var div_length = $('.container .apple').length;
    var rand = Math.floor(Math.random() * div_length);
    if($(".container").children().length > 0)
        $(".container .apple:eq("+rand+")").after(jQuery('.wrapper').html()).attr('rand',rand);
    else
        $(".container").append(jQuery('.wrapper').html());
  });

 Note : I have taken wrapper to .apple class and have fired click event on button to append div