我有两个div,我想在其中只有一个随机添加“.active”类。
这是我能想到的最好的,但是,有时两个div都会添加这个类。
randomClass: function(){ var classes = ["active", ""]; $(".contain > div").each(function(){ $(this).addClass(classes[~~(Math.random()*classes.length)]); }); },HTML
<div class="contain"> <div></div> <div></div> </div>I have two divs and I want to add the class ".active" to only one of them at random.
This is the best I could come up with, however, sometimes both divs get the class added.
randomClass: function(){ var classes = ["active", ""]; $(".contain > div").each(function(){ $(this).addClass(classes[~~(Math.random()*classes.length)]); }); },HTML
<div class="contain"> <div></div> <div></div> </div>最满意答案
我编写了以下代码来使用eq。 它将在有效索引之间选择一个随机数,然后返回该值,然后附加适当的类。 我添加了一行来删除当前该类处于活动状态的那一行,因此该按钮可以正常工作。
您的代码的重要逻辑错误 :通过使用.each,您不能保证不选择两者或不选择。 你必须事先选择对象。
使用您的代码 ,这里是可能的out(其中1是活动的,0是不活动的):
1 0 0 1 1 1 0 0您的代码有50%的可能无法正常工作。
所以,我写的有点不同。
function randomClass(){ $(".contain > div").removeClass("active"); $(".contain > div").eq(Math.floor(Math.random()*$(".contain > div").length)).addClass("active"); } randomClass();.active { background-color:red; } .box { width:50px; height:50px; border:1px solid black; margin:10px; }<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="contain"> <div class="box"></div> <div class="box"></div> </div> <button onclick="randomClass()">New Random</button>I wrote the following code to use the eq. It will select a random number between the valid indexes and then return that value and then append the proper class. I added one line to remove whichever one currently has the class active, so the button would work.
Important logic error with your code: by using .each you are not guaranteeing that both or none are not selected. You have to select the object before hand.
With your code, here is the possible out comes (where 1 is active and 0 is not active):
1 0 0 1 1 1 0 0There is a 50% chance your code will not work as intended.
So, I wrote mine a little differently.
function randomClass(){ $(".contain > div").removeClass("active"); $(".contain > div").eq(Math.floor(Math.random()*$(".contain > div").length)).addClass("active"); } randomClass();.active { background-color:red; } .box { width:50px; height:50px; border:1px solid black; margin:10px; }<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="contain"> <div class="box"></div> <div class="box"></div> </div> <button onclick="randomClass()">New Random</button>
更多推荐
发布评论