Any way to shuffle content in multiple div elements

前端 未结 8 1076
鱼传尺愫
鱼传尺愫 2020-12-31 23:32

I\'m relatively new to Javascript and was wondering if there\'s a quick way to shuffle content that is contained in multiple

tags. For example

相关标签:
8条回答
  • 2021-01-01 00:19

    are you ok with using a javascript library like jQuery? here's a quick jQuery example to accomplish what you're after. the only modification to your HTML is the addition of a container element as suggested:

    <div id="shuffle">
        <div id='d1'>...</div>
        <div id='d2'>...</div>
        <div id='d3'>...</div>
    </div>
    

    and javascript:

    function shuffle(e) {               // pass the divs 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 our set
           replace.append(temp);        // add the selected div to our new set
           e = e.not(temp); // remove our selected div from the main set
           size--;
        }
        $('#shuffle').html(replace.html() );     // update our container div with the
                                                 // new, randomized divs
    }
    
    shuffle( $('#shuffle div') );
    
    0 讨论(0)
  • 2021-01-01 00:28

    You can grab the content of each div

    c1 = document.getElementById('div1').innerHTML
    c2 = document.getElementById('div2').innerHTML
    c3 = document.getElementById('div3').innerHTML
    

    Then determine a new order for them randomly .. and then put each content in the new destination

    say for instance, the randomness gave:

    c1_div = 'div2'
    c2_div = 'div1'
    c3_div = 'div3'
    

    then you just:

    document.getElementById(c1_div).innerHTML = c1
    document.getElementById(c2_div).innerHTML = c2
    document.getElementById(c3_div).innerHTML = c3
    
    0 讨论(0)
提交回复
热议问题