Randomizing the order of divs on page load with jq

2019-09-11 14:09发布

This question already has an answer here:

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!

3条回答
forever°为你锁心
2楼-- · 2019-09-11 14:32

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];    
}
查看更多
手持菜刀,她持情操
3楼-- · 2019-09-11 14:36

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]);
}
});
查看更多
淡お忘
4楼-- · 2019-09-11 14:48

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

查看更多
登录 后发表回答