jQuery add numbered class recursively to blocks of

2019-08-06 13:08发布

问题:

I'm dinamically wrapping a fixed number of divs from an array (e.g. 4 in each group). The number of .item div's returned from the array is unknown... I need to recursively add the same class to those groups of divs wrapped toghether:

<div class="wrapper">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
<div class="wrapper">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
<!-- more divs follow... -->
<div class="wrapper">
   ...
</div>
<div class="wrapper">
   ...
</div>

and this is tghe final result:

<div class="wrapper">
  <div class="item div-01"></div>
  <div class="item div-02"></div>
  <div class="item div-03"></div>
  <div class="item div-04"></div>
</div>
<div class="wrapper">
  <div class="item div-01"></div>
  <div class="item div-02"></div>
  <div class="item div-03"></div>
  <div class="item div-04"></div>
</div>
<!-- more divs follow... -->
<div class="wrapper">
   ...
</div>
<div class="wrapper">
   ...
</div>

the code I'm using to wrap the divs:

var divs = $(".item");
for(var i = 0; i < divs.length; i+=4) {
    divs.slice(i, i+4).wrapAll('<div class="wrapper"></div>');
}

回答1:

Try this:

// For each `.wrapper`
$('.wrapper').each(function() {

    // Get all the `.item` inside this `.wrapper`
    $(this).find('.item').each(function () {
        var class = ($(this).index()) > 9 ? $(this).index() : 0 + $(this).index();
        $(this).addClass('div-' + class);
        // Add class using the `index()` of this element
    });
});

DEMO



回答2:

$('.wrapper').each(function() {
    $.each($(this).children('.item'), function(k,v) { // k = index, v = value
        $(this).addClass('div-' + (k < 9 ? '0' : '') + (k+1));
    });
});

Loop over the items using the each() and add the class using the index.



回答3:

Here is my old-school 2-D loop solution. Looping over class wrapper and then on item.

var i = 0;
$('.wrapper').each(function () {
    $(this).find('.item').each(function () {
       i++;
       $(this).addClass("item-"+i);
    });
    i = 0;
});

FIDDLE