[英]Add class to every few random elements with jquery
I have a sequence of elements, let's say: 我有一系列元素,可以这样说:
<div class="tile1"></div>
<div class="tile2"></div>
<div class="tile3"></div>
<div class="tile4"></div>
etc. 等等
How would I use Jquery to add the new class "color" to every few random elements with an increment varying between 2 and 6 like so: 我将如何使用Jquery将新类“颜色”添加到每几个随机元素中,其增量在2到6之间变化,如下所示:
<div class="tile1"></div>
<div class="tile2 color"></div>
<div class="tile3"></div>
<div class="tile4"></div>
<div class="tile5 color"></div>
<div class="tile6"></div>
<div class="tile7 color"></div>
<div class="tile8"></div>
<div class="tile9"></div>
<div class="tile10"></div>
<div class="tile11"></div>
<div class="tile12 color"></div>
etc. 等等
This will add your random color class to your divs as well as your index 这会将您的随机颜色类别添加到div以及索引中
$( "div" ).addClass(function( index ) {
return "tile" + index + (Math.floor(Math.random() * 10 + 1) == 2) ? '' : 'color';
});
You'll need to mix JQuery with plain javascript: 您需要将JQuery与纯JavaScript混合使用:
$("[class^=tile]").each(function(i,e){
ranNum = Math.floor(Math.random() * (6 - 2 + 1)) + 2;
if((i + 1) % ranNum == 0){
$(e).addClass('color');
}
});
Here we're looping through the tile divs and if the remainder of the tile's number divided by the random number is 0 we're assigning it the color class. 在这里,我们遍历图块div,如果图块数除以随机数的余数为0,我们将为其分配颜色类别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.