开发者

jQuery - After number of elements add html!

I need to know if I can count the elements inside a div and after 3 elements开发者_StackOverflow社区 to add an html object.

<div id="wrapper">
<a href="#">1</a>
<a href="#">1</a>
<a href="#">1</a>
//insert html with jQuery here
<a href="#">1</a>
<a href="#">1</a>
<a href="#">1</a>
//insert html with jQuery here
<a href="#">1</a>
<a href="#">1</a>
<a href="#">1</a>
//insert html with jQuery here
</div>


$('#wrapper a').each(function(i,e){
  if (((i+1) % 3) == 0)
    $(this).after('<p>Hello, world.</p>');
});

Take advantage of .each's "i" parameter that gives you element index. Than you can use Modulo to get the 3rd item and append.

Working example: http://www.jsfiddle.net/hd7FP/1/

at this point just showing an alternative solution


Take a look at the nth-child-selector.

Basically:

$("#wrapper a:nth-child(3n)").after("<span>I'm new.</span>");


$('#wrapper a').each(function(index) {
  if ((index+ 1) % 3 == 0)
     $(this).after(content);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜