Randomizing the order of divs on page load with jq

2019-09-11 14:06发布

问题:

This question already has an answer here:

  • Randomize children elements on load 3 answers

I'm working on my first website (personal use for my portfolio). I have content in divs, but want them to reorder in randomly each time the page is reloaded. I tried to search for solutions, found a few similar questions, but didn't get anything to work (maybe it's because my content has multiple classes?).

what i have inside the body tags is is:

<div class="box work_self work_all">
<img src="1.jpg' />
</div>
<div class="box work_group work_all">
<img src="2.jpg' />
</div>
<div class="box work_group work_all">
<img src="3.jpg' />
</div>

[...]and so on.

Help is appreciated! Thanks!

回答1:

The following will get them out of the dom and print them back out randomly.

$(document).ready(function() {
//get list of divs
var div = $(".box").toArray();

//randomly print them back out.
while(div.length > 0) {
    var idx = Math.floor((Math.random() * (div.length-1)));
    var element = div.splice(idx, 1);
    $('body').append(element[0]);
}
});


回答2:

Try this:

var divs = [];
var divs_shuffle = shuffle($('.box').get());
for(var i in divs_shuffle){
  divs.push(divs_shuffle[i].outerHTML);
}
$('body').html(divs.join(''));

You can find shuffle() function here https://stackoverflow.com/a/6274398/2604607



回答3:

Sorry for the late, response, I hope this still helps you. Here you have a live fiddle: http://jsfiddle.net/J5z4n/1/ and below you have the source code. You may replace 10 with another number bigger than your number of elements. The idea is to save the innerHTMLs of the target tags and then swap them.

var elements = $("div");
var elementsInnerHtmls = [];
var numberOfElements = elements.length;

for( var i = 0 ; i < numberOfElements ; i++){
    elementsInnerHtmls.push(elements[i].innerHTML); 
}

var checkedIndexes = [];
for( var i = 0 ; i < numberOfElements ; i++){
    var randomIndex = Math.floor(Math.random()*10) % numberOfElements;
    while(checkedIndexes[randomIndex] != undefined){
        randomIndex = Math.floor(Math.random()*10) % numberOfElements;    
    }
    checkedIndexes[randomIndex] = true;
    elements[i].innerHTML = elementsInnerHtmls[randomIndex];    
}