2010-06-18 88 views
3

不要問爲什麼,但我需要添加類斑馬到<li>元素旁邊的內容。這是據我已經得到了,但我不知道該怎麼計算中使用:如何爲每個4th-1元素添加一個類?

$("li").each(function(index){ 
    if(index % ??? == 0) { // <-- not sure what to put here 

    } 
}); 
<ul> 
    <li></li> 
    <li></li> 
    <li></li> <!-- add the zebra class here --> 
    <li></li> 
    <li></li> 
    <li></li> 
    <li></li> <!-- add the zebra class here --> 
    <li></li> 
    <li></li> 
    <li></li> 
    <li></li> <!-- add the zebra class here --> 
    <li></li> 
</ul> 

誰能幫助?

+0

普通斑馬或只是對那些有內容?請詳細說明你的問題! – 2010-06-18 09:24:25

+0

您顯示3,4,4。這是3或4?什麼是索引?請記住,模數是餘數。所以,如果3%1 = 2,3%2 = 1,3%3 = 0 – 2010-06-18 09:25:59

+0

就在哪裏有評論。索引2處的第一斑馬,然後是3索引後面的斑馬 – chchrist 2010-06-18 09:26:51

回答

12

:nth-child()選擇可以接受的公式,它完美地解決您的問題:

$('ul li:nth-child(4n+3)').addClass("zebra").text("Here"); 

選擇每4個li開始在3日起,:nth-child(4n-1)也將工作(每4個1元)。沒有each()或modulo必要。

http://jsfiddle.net/AvPhe/ - 例如基於你的樣品輸入時,斑馬類是與文本「在這裏」一起加入。

+1

++比其他答案更簡潔:) – Jeriko 2010-06-18 09:43:16

+0

非常感謝。我不知道關於第n個孩子的選擇器。在我的情況下,雖然它是(4n + 2) – chchrist 2010-06-18 09:57:38

+0

@christ:這是一個很酷的選擇器:-)你在這個問題中給出的例子是(4n + 3),所以我只用了它(檢查小提琴鏈接)。 – 2010-06-18 10:22:06

0

週期爲4,因此模應該是4
但是它是由兩個偏移,所以你需要添加2指數:

if ((index + 2) % 4 == 0) 
2

從我可以告訴,你要第3 ,第7,第11,...帶班 「斑馬」:

$("li").each(function(index,item){ 

if((index+2)%4 == 0) { 
    $(item).addClass("zebra"); 
} 

}); 

編輯:請查閱Andy的回答。比我的好多了:-)

0
if (index % 4 == 2) 

是我想你在找的東西。

在你的例子中,你選擇了第3,第7和第10個元素。

相關問題