Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

javascript - 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>

After Shuffle:

<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>

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
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();     

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);

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...