随机洗同一个班级的所有DIVS [英] Shuffle all DIVS with the same class
问题描述
我需要做的是: 原始状态:
What I need done is: Original State:
<div class="shuffledv">
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
</div>
<div class="shuffledv">
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
</div>
随机播放后:
<div class="shuffledv">
<div id="2"></div>
<div id="3"></div>
<div id="1"></div>
</div>
<div class="shuffledv">
<div id="5"></div>
<div id="4"></div>
<div id="6"></div>
</div>
第一个div内的Divs留在那里,但被洗牌,第二个具有相同班级的div也会发生同样的情况. 要将特定div内的div随机播放,请使用以下命令:
The Divs within the first div stay there but get shuffled, and the same happens for the second div with the same class. To shuffle divs inside a specific div I use something like this:
function shuffle(e) { // pass divs inside #parent to the function
var replace = $('<div>');
var size = e.size();
while (size >= 1) {
var rand = Math.floor(Math.random() * size);
var temp = e.get(rand); // grab a random div from #parent
replace.append(temp); // add the selected div to new container
e = e.not(temp); // remove our selected div from #parent
size--;
}
$('#parent').html(replace.html()); // add shuffled divs to #parent
}
这叫谎言:shuffle('#parent .divclass')
所有类divclass
的Divs都在#parent
内部
我认为应该以类似的方式开始
Called lie this: shuffle('#parent .divclass')
Where all Divs with class divclass
are inside #parent
I think it should start out something like
function shuffle() {
$(".shuffledv").each(function() {
,然后执行某种形式的原始功能,但现在我已经完全迷路了.我不知道如何从这里前进.请让我知道是否需要更多信息.
and then do some form of the original function, but I've just gotten completely lost at this point. I have no idea how to go forward from here. Please let me know if you need anymore info.
推荐答案
看看此jsfiddle 一个>.本质上,我们对每个容器shuffledv
div执行的操作是找到所有子div并将其存储在列表中,然后从DOM中删除它们,例如:
Take a look at this jsfiddle. Essentially what we do is for each of the container shuffledv
divs we find all children divs and store them in a list, then we remove them from the DOM, e.g.:
$(".shuffledv").each(function(){
var divs = $(this).find('div');
for(var i = 0; i < divs.length; i++) $(divs[i]).remove();
然后,我从此处抓取了Fisher-Yates改组算法以进行随机化div列表,最后我们将它们附加回父容器,如下所示:
Then I grabbed the Fisher-Yates shuffling algorithm from here to randomise the list of our divs, and finally we append them back to the parent container, like this:
for(var i = 0; i < divs.length; i++) $(divs[i]).appendTo(this);
希望这会有所帮助!
这篇关于随机洗同一个班级的所有DIVS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!