这就是我所拥有的:
$(function(){
$('.apple').appendTo('.container');
});
现在,假设我有 20 个不同的 div,其类名为 .apple。
如何将它们随机 append 到容器中?因此,每次加载页面时,顺序都会不同。
提前谢谢您!
最佳答案
您可以通过获取一些随机
值来尝试下面的代码,并将其用于if/else
条件:
$(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
关于javascript - 随机化我追加到另一个 div 中的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25029503/