简体   繁体   English

从数组值中将div包装到div中

[英]Wrap div inside div from array values

First of all Hello to everyone, and sorry for my English. 首先,大家好,对不起我的英语。
I have ten divs an i want wrap them in groups inside a div with class="group" 我有十个div,我想用class =“ group”将它们包装在一个div中的组中
The amount of div inside various divs. 各种div内的div数量。 group depends on the values in an array 组取决于数组中的值
So if array is:[2,3,4,1] the result would be: 因此,如果array为:[2,3,4,1],则结果为:

<div class="group">
    <div></div>
    <div></div>
</div>    

<div class="group">      
    <div></div>
    <div></div>
    <div></div>
</div>    

<div class="group">       
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

<div class="group">      
    <div></div>
</div>

I am able to get the desired result having an array that specifies the closing position of the different tag group [2,5,9,10] 我能够获得具有指定不同标签组[2,5,9,10]的关闭位置的数组的期望结果
But since today my brain doesn't seem works, i'm not able to achieve the same result with the first array [2,3,4,1]. 但是由于今天我的大脑似乎无法正常工作,所以我无法通过第一个数组[2,3,4,1]达到相同的结果。
Any answer will be read with pleasure, thank you all. 任何答案都会令人愉快地阅读,谢谢大家。 code with second array: 第二个数组的代码:

var ranges=[2,5,9,10]
    for(i=0;i<ranges.length;i++){
        var a=0
        var b=0
        if(ranges[i]===2){ a=0; b=2}
        else{a=ranges[i-1]; b=ranges[i]}
        console.log(a,b)
        divs.slice(a, b).wrapAll("<div class='group'></div>");
        }

You can use a start variable and a loop like this 您可以使用一个start变量和一个这样的循环

var $divs = $('div'),
    start = 0;
$.each(array, function (i, val) {
    $divs.slice(start, start + val).wrapAll('<div class="group" />');
    start += val;
})

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM