Count the number of elements with a specific class

2019-08-22 15:26发布

问题:

I'm very new to this, just trying to piece together snippets from other posts.

I'm unsure how to count the number of elements on a page, then add a class to differentiate them with a number.

<script type="text/javascript">
$(document).ready(function(){
    $('.item').each(function (e) { $(this).addClass('count' + e); });
});
</script>

<div class="item"></div>
<div class="item"></div>
<div class="item"></div>

output to:

<div class="item count1"></div>
<div class="item count2"></div>
<div class="item count3"></div>

回答1:

Try this

$('div.item').each(function(i,n){ $(n).addClass('count' + (i + 1));});


回答2:

Try this:

$('.item').each(function (i, e) { $(e).addClass('count' + i); });


回答3:

$('.item').addClass(function(i){
    return "count" + (i + 1);
});


回答4:

What you have is just fine if you just change:

$(this).addClass('count' + e);

to

$(this).addClass('count' + (e + 1));