jQuery以递归方式将数字类添加到div的块 [英] jQuery add numbered class recursively to blocks of divs

查看:99
本文介绍了jQuery以递归方式将数字类添加到div的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数组中包装了固定数量的div(例如每组4个)。
从数组返回的 .item 的数目是未知的...
我需要递归地将相同的类添加到这些divs包toghether:

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>

这是最终结果:

<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>

我用来封装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>');
}


推荐答案

>

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

这篇关于jQuery以递归方式将数字类添加到div的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆