Randomize the divs that I append into another one

2019-06-05 02:56发布

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!

7条回答
放荡不羁爱自由
2楼-- · 2019-06-05 03:24
$.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/

查看更多
虎瘦雄心在
3楼-- · 2019-06-05 03:25

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

查看更多
老娘就宠你
4楼-- · 2019-06-05 03:31

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

查看更多
男人必须洒脱
5楼-- · 2019-06-05 03:32

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)); 
});
查看更多
欢心
6楼-- · 2019-06-05 03:34

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;
}
查看更多
【Aperson】
7楼-- · 2019-06-05 03:37

Use like this:

var idx;
$('.apple').each(function(){
   idx = Math.floor(Math.random() * 20) +1;
   $(this).eq(idx).appendTo('.container');
});
查看更多
登录 后发表回答