2011-02-23 47 views
1

我有一些div的像jQuery - 每個div都有3個href!

<div class="block-wrap"> 
<a href="#">A</a> 
<a href="#">A</a> 
<a href="#">A</a> 
<a href="#">A</a> 
<a href="#">A</a> 
<a href="#">A</a> 
</div> 

<div class="block-wrap"> 
<a href="#">A</a> 
<a href="#">A</a> 
<a href="#">A</a> 
<a href="#">A</a> 
<a href="#">A</a> 
<a href="#">A</a> 
</div> 

和一個jQuery。

$('div.block-wrap a').each(function(index) { 
    if ((index+ 1) % 3 == 0) 
    $(this).after("<span></span>"); 
}); 

此廣告後3 A HREF的跨度,但如果我有一個div僅有2 A HREF,這將在未來DIV一個A HREF後添加範圍。 我需要爲每個div分別製作此計數。 任何人都可以幫忙嗎? 謝謝!

回答

6

爲每個block-wrap做一個單獨的迭代。

例子:http://jsfiddle.net/Q5Bzj/1/

$('div.block-wrap').each(function() { 
    $(this).children('a').each(function(index) { 
    if ((index+ 1) % 3 == 0) 
     $(this).after("<span></span>"); 
    }); 
}); 

如果希望每個block-wrap與一個<span>不管什麼目的,你可以這樣做:

例子:http://jsfiddle.net/Q5Bzj/

$('div.block-wrap').each(function() { 
    $(this).children('a').each(function(index) { 
    if (index % 3 == 2) 
     $(this).after("<span></span>"); 
    }).end().children('a:last-child').after("<span></span>"); 
}); 
+1

你很快! +1的速度,也提煉了'a'選擇器(可能是OP想要的)。 – alex 2011-02-23 01:29:08