简体   繁体   中英

Randomly select remaining divs Javascript

I have three divs with the attribute row . When the page loads I want to randomly select one of the divs and apply the class .show . From here, when the document is clicked I want one of the divs out of the remaining two divs to be randomly selected and have the class .show applied to it. When the document is clicked again, the last remaining div showed have .show applied to it. Now all three divs have the class .show . If the document is clicked again visual cycle should be restart so that only one randomly selected div has the class .show .

I've laid out (as a javascript novice) my approach but I don't know how to keep track of the rowArray which records which divs are remaining (the divs that DONT have the class .show ) at each stage of the counter.

Any pointers in the right direction would be greatly appreciated. I have attached a JSFiddle with comments.

 var selector = Math.floor((Math.random() * 3)); var rowArray = [0, 1, 2]; var counter = 0; $(document).ready(function() { counter++ $('#cnt').find("div[row=" + selector +"]").addClass('show'); var newrowArray = rowArray.splice(selector, 1); $(document).on("click", function() { counter++ if (counter ==1 ) { } else if (counter == 2) { } else { counter = 1; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="cnt"> <div row="0"></div> <div row="1"></div> <div row="2"></div> </div> 

you can make a function that selects all the elements that do not have show class, using this list select a randomIndex and then randomly add class show to one these elements. You can all this function on page load and from click on document.

 $(document).ready(function() { function selectDiv(){ var notSelectedDivs = $("div[row]:not(.show)"); if(!notSelectedDivs.length){ $('.show').removeClass('show'); notSelectedDivs = $("div[row]:not(.show)"); } var randomIndex = Math.floor((Math.random() * notSelectedDivs.length)); $(notSelectedDivs[randomIndex]).addClass('show'); } $(document).on("click", function() { selectDiv(); }); selectDiv(); }); 
 .show{ color: #ff0000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="cnt"> <div row="0">1</div> <div row="1">2</div> <div row="2">3</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM