开发者

jquery add or slice

I am trying to wrap a certain number of elements in a div. The problem is that the number of elements can vary based on the user's input. So the number of elements could be 2, 3, 4, or even more. I have a variable that tells me how many elements should be wrapped. So, for instance, my page may have this:

<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>

Now I need to wrap those in another div based on my variable. So, if my variable held a value of 3, it would look like this:

   <div class="testing"> 
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>   
   </div>

   <div class="testing">
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
   </div>

I was using this code:

$(this).add($(this).next())
       .add($(this).next().next())
       .wrapAll('<div class="testing"></div>');

The problem with that is that I would need to know how many elements are going to be there. Is there a dynamic way to do this? I also saw the slice function and tried to use it like this:

for(var i=0;i<img_cnt;i+=img_row){
    obj.children().slice(i,i+img_row).wrapAll('<div class="row"></div>');
}

It is not working, though. I have 8 divs. It should be wrapping 3 together, so I should have 3 new divs with 3 in t开发者_运维技巧he first 2 and 2 in the last, since there are only 8 divs. However, I get 3 divs in the first new div, then the next 2 divs are not wrapped at all, and then the last 3 divs are wrapped in a new div. I am not sure why it is not wrapping it right. Do you have any ideas on how to do this or maybe even a better method?


Your code isn't working because children is changing. Try using slice on a constant set:

var all = $('.test'); 
for(i=0; i < all.length; i += img_row) {
   all.slice(i, i + img_row).wrapAll('<div class="row" />'); 
}

Example: http://jsbin.com/upaji

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜