admin管理员组

文章数量:1303498

Hoping someone can help as I do not know much about JS

I have 3 divs

 <div id="content1">This is content 1 </div>
 <div id="content2">This is content 2 </div>
 <div id="content2">This is content 2 </div>

I require some JS that randomly loads one of those divs on page load and hide the other two

Any help would be much appreciated

Thanks

Hoping someone can help as I do not know much about JS

I have 3 divs

 <div id="content1">This is content 1 </div>
 <div id="content2">This is content 2 </div>
 <div id="content2">This is content 2 </div>

I require some JS that randomly loads one of those divs on page load and hide the other two

Any help would be much appreciated

Thanks

Share Improve this question asked Feb 9, 2015 at 15:15 user3660176user3660176 371 silver badge2 bronze badges 3
  • This question should help you : stackoverflow./questions/20046687/… – HavelTheGreat Commented Feb 9, 2015 at 15:18
  • Generate a random number. PIck the one generated, show it. – epascarello Commented Feb 9, 2015 at 15:18
  • @Elizion This question is probably a duplicate of that one. Voting to close. – ssube Commented Feb 9, 2015 at 15:20
Add a ment  | 

1 Answer 1

Reset to default 8

You can select all div elements when the page loads, then pick a random one to keep and hide the rest.

var elems = $("div");
if (elems.length) {
  var keep = Math.floor(Math.random() * elems.length);
  for (var i = 0; i < elems.length; ++i) {
    if (i !== keep) {
      $(elems[i]).hide();
    }
  }
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="content1">This is content 1  </div>
<div id="content2">This is content 2  </div>
<div id="content3">This is content 3  </div>

本文标签: htmljavascriptrandom div on page loadStack Overflow