简体   繁体   中英

Adding different classes to each list item

I've created a list and am trying to add a different class name to each one. Currently, I'm using this method:

HTML:

<ul class="sd-list">
   <li><a href="#">List Item 1</a></li>
   <li><a href="#">List Item 2</a></li>
   <li><a href="#">List Item 3</a></li>
</ul>

jQuery:

$('.sd-list:nth-child(1)').addClass('green');
$('.sd-list:nth-child(2)').addClass('red');
$('.sd-list:nth-child(3)').addClass('purple');

This works fine, but I'm wondering if there is a better method than the one I'm currently using. Any help would be greatly appreciated.

You can put the classes in an array:

var colors = ['green', 'red', 'purple'];

$('.sd-list').each(function() {
    var index = $(this).index();
    if (index < colors.length) {
        $(this).addClass(colors[index]);
    }
});

If the lists are all children of the same parent and you used :nth-child(X) to get the element at position X (instead of truly using it as "the n-th child of parent" ), and you have a class for each position, you can also simplify it to:

$('.sd-list').addClass(function(index) {
    return colors[index];
});

But I agree with Vlad, you can easily write this directly in CSS:

.sd-list:nth-child(1) {
    /* rules */
}
/* etc */
$(function () {

      $(".sd-list li").each(function(index) {
            $(this).attr("class", "color" + index);
      });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM