简体   繁体   中英

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:

<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" ).addClass(function( index ) {
      return "tile" + index + (Math.floor(Math.random() * 10 + 1) == 2) ? '' : 'color';
  });

You'll need to mix JQuery with plain 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.

JSFIDDLE

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