简体   繁体   English

随机选择剩余的divs Javascript

[英]Randomly select remaining divs Javascript

I have three divs with the attribute row . 我有三个div属性row When the page loads I want to randomly select one of the divs and apply the class .show . 当页面加载时,我想随机选择一个div并应用.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. 从这里开始,单击文档时,我希望从其余两个div中随机选择一个div,并.show应用.show类。 When the document is clicked again, the last remaining div showed have .show applied to it. 再次单击该文档时,显示的最后一个剩余div已应用.show Now all three divs have the class .show . 现在,所有三个div都具有类.show If the document is clicked again visual cycle should be restart so that only one randomly selected div has the class .show . 如果再次单击该文档,则应重新启动可视循环,以使只有一个随机选择的div具有.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. 我已经设计了(作为javascript新手)我的方法,但是我不知道如何在计数器的每个阶段跟踪rowArray ,该rowArray记录剩余的div(DONT的div具有.show类)。

Any pointers in the right direction would be greatly appreciated. 朝正确方向的任何指针将不胜感激。 I have attached a JSFiddle with comments. 我在JSFiddle上附加了评论。

 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. 您可以使一个函数选择所有没有show类的元素,使用此列表选择一个randomIndex,然后将class show随机添加到这些元素之一。 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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