开发者

In Jquery, how do I apply a class to every third (or fourth) instance of an element with a particular class?

开发者 https://www.devze.com 2023-02-19 10:30 出处:网络
This is what I\'m trying to do: http://jsfiddle.net/ZfwPT/ i.e. make every first, sixth, eleventh, etc element with class \"Noted\" green,

This is what I'm trying to do: http://jsfiddle.net/ZfwPT/

i.e. make every first, sixth, eleventh, etc element with class "Noted" green, and make every second, seventh, twelfth, etc. element with class "Noted" blue, and so on.

I've been trying 开发者_Go百科to use eq() but I think I'm doing something wrong:

$('span.Noted').eq(n/5).addClass('Note'n)

which to me means, take the number the item has (whether it's #5 or #100 in the series) and divide it by five, and then use that number to assign it a class. Then in CSS I have Note1 {color:green} etc.

There must be an easier way of doing this, right?


You can do like that:

$(function(){
    $('p:nth-child(5n+1) span.Noted').addClass('Note1');

    $('p:nth-child(5n+2) span.Noted').addClass('Note2');

    $('p:nth-child(5n+3) span.Noted').addClass('Note3');

    $('p:nth-child(5n+4) span.Noted').addClass('Note4');

    $('p:nth-child(5n) span.Noted').addClass('Note5');
});

Working example here: http://jsfiddle.net/ZfwPT/7/


Use something like:

$('span.Noted').each(function(i){
 $(this).attr("id", "Note"+(i+1));
});

As you can see here -> http://jsfiddle.net/ZfwPT/6/


try this:

// how much span should be grouped to one class
var blocksize = 5;

$('span.Noted').each(function(i) {
    $(this).addClass("Note" + Math.ceil((i + 1) / blocksize));
});
0

精彩评论

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

关注公众号