Randomly display content in a div after refresh

2019-06-05 21:44发布

问题:

I want to have a div that randomly displays content after refresh. I found a code that kind of worked, but it doesn't 100% work, so I'm trying to find the error here.

I was asked to post this as a new topic after using the code of [this] (randomly display a div class using JQuery) question, but it did not work properly.

Code in the header:

window.onload=function() {
  var E = document.getElementsByClassName("item");
  var m = E.length;
  var n = parseInt(Math.random()*m);
  for (var i=m-1;i>=0;i--) {
  var e = E[i];
  e.style.display='none';
  }
  E[n].style.display='';
}

in the body I have the following

<div class="item">Lorem ipsum dolor</div>
<div class="item">Lorem ipsum dolor sit amet</div>
<div class="item">Lorem ipsum </div>
<div class="item">Lorem </div>

When loading the page it displays all of the item-divs and then after the rest is loaded (the divs are at the very top) all except for one are hidden.

Why is this happening? how does the code need to be changed so the other contents aren't displayed at all?

回答1:

The reason your code doesn't work is because all your item div's are visible when the page loads. you need to hide them in the .item css using display: none;

since you've tagged JQuery as well, you can update your JS like this

$(function(){
    var random = Math.floor(Math.random() * $('.item').length);
    $('.item').eq(random).show();    
});

I've put up a working JSFIDDLE with some styling. Hope this helps



回答2:

Instead of keeping all your divs visible and your script hiding some - let all the divs be hidden in the beginning and make your script show just the random one.
To do this, just add the following style to your HTML along with your existing code:

.item{
display:none;
}

I think this should work.



标签: jquery random