开发者

JQuery to add divs to list of images

Hey I have a list of images that I need to wrap with divs so that every three images is in a new div. The first div has to start at the beginning and continue for the next three images before closing and opening the next div. The final HTML should look like this:

<div>
    <img />
    <img />
    <img />
</div>
<div>
    <img />
    <img />
    <img />
</div>
<div>
    <img />
    <img />
    &开发者_StackOverflowlt;img />
</div>

I know that this should have to do something with the nth child selector but so far I've only been able to select single elements rather then being able to select three at a time.


well,

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

demo


You could do something like the following:

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


Assuming those images are in a container with the ID container, you could do this:

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜