2011-01-19 130 views
1

嘿,我有一个图像列表,我需要与div包装,使每三个图像在一个新的div。第一个div必须从开始处开始,然后在关闭并打开下一个div之前继续处理接下来的三张图像。最后的HTML应该是这样的:JQuery将div添加到图像列表

<div> 
    <img /> 
    <img /> 
    <img /> 
</div> 
<div> 
    <img /> 
    <img /> 
    <img /> 
</div> 
<div> 
    <img /> 
    <img /> 
    <img /> 
</div> 

我知道这应该做一些与第n个孩子选择,但到目前为止,我只能够选择单个元素,而然后能够选择三个在一次。

+0

你给呐决赛,但什么是最初的? – Reigel 2011-01-19 02:25:44

回答

0

你可以做类似如下:

var imgListLength = $imageList.length, // assuming $imageList is your jQuery object 
    tmpArray = $imageList.toArray(), 
    newHtml = ''; 

for (var i = 0; i < imgListLength; i = i + 3) { 
    newHtml += '<div>'; 
    newHtml += tmpArray[i] + tmpArray[i + 1] + tmpArray[i + 2]; 
    newHtml += '</div>'; 
} 

$('body').append(newHtml); 
2

好,

$('img:nth-child(3n)').each(function(){ 
    $(this).prevAll('img').andSelf().wrapAll('<div/>'); 
}); 

demo

+0

jQuery非常漂亮。 – Jeff 2011-01-19 02:42:51

0

假设这些图像是在与ID container的容器,你可以这样做:

例如:http://jsfiddle.net/c2nQH/

var imgs = $('#container > img'); 

imgs.each(function(i) { 
      // If we're on a multiple of 3... 
    if (i % 3 == 0) { 
       // ...take a slice of it and the next two, and wrap them. 
     imgs.slice(i, i + 3).wrapAll('<div></div>'); 
    } 
}); 
+0

嘿,我用帕特里克dw例子,它解决了。谢谢! – msegreto 2011-01-19 23:43:49