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:41
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
查看更多
登录 后发表回答