Count the number of elements with a specific class, then add an ID that numbers them

青春壹個敷衍的年華 提交于 2019-12-11 18:43:49

问题


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));


来源:https://stackoverflow.com/questions/11478777/count-the-number-of-elements-with-a-specific-class-then-add-an-id-that-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!