如何计算具有特定类的元素数量,并使用jquery将每个元素的计数添加为新的类名?
$('.full-screen').each(function(i) {
$(this).addClass('.full-screen-', i);
});
我想创建:
<div class="full-screen full-screen-1"></div>
<div class="full-screen full-screen-2"></div>
<div class="full-screen full-screen-3"></div>
<div class="full-screen full-screen-4"></div>
<div class="full-screen full-screen-5"></div>
答案 0 :(得分:1)
你可以做到
client__projects
$('.full-screen').each(function(i) {
$(this).addClass('full-screen-'+(i+1));
});
&#13;
$('.full-screen').each(function(i) {
$(this).addClass('full-screen-'+(i+1));
console.log($(this)[0].outerHTML)
});
&#13;
答案 1 :(得分:1)
此外,您可以使用.addClass( function )
代替.each()
$('.full-screen').addClass(function(i) {
return 'full-screen-'+(i+1);
});
$('.full-screen').addClass(function(i) {
return 'full-screen-'+(i+1);
});
console.log($('.full-screen'))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="full-screen"></div>
<div class="full-screen"></div>
<div class="full-screen"></div>
<div class="full-screen"></div>
<div class="full-screen"></div>
&#13;
答案 2 :(得分:1)
试试这个
$(".full-screen").each(function((i){
$(this).addClass("full-screen-" + (i+1));
});