gpt4 book ai didi

javascript - 使用 jquery 计算特定元素并向类名添加计数

转载 作者:可可西里 更新时间:2023-11-01 12:58:29 24 4
gpt4 key购买 nike

如何使用 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>

最佳答案

您也可以使用 .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'))
<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>

关于javascript - 使用 jquery 计算特定元素并向类名添加计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45481740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com