gpt4 book ai didi

jquery - 使用jquery增加每个元素的属性值(int)

转载 作者:行者123 更新时间:2023-12-01 00:33:55 32 4
gpt4 key购买 nike

我有未知数量的部分元素:

<section id="foo">
...
</section>

<section id="bar">
...
</section>

对于存在的每个部分,我需要添加一个属性“data-serial”,它是一个从 0 开始的整数,并且对于存在的每个部分递增 1,例如上面的内容将变成:

<section id="foo" data-serial="0">
...
</section>

<section id="bar" data-serial="1">
...
</section>

<section id="bla" data-serial="2">
...
</section>
...

如何使用 jQuery 实现此目的?

谢谢

最佳答案

var current = 0;
$("section").each(function() {
$(this).data("serial", current);
current++;
});

这会循环遍历文档中的所有 section 元素,并使用 jQuery data 方法将 current 的值附加到每个元素。

关于jquery - 使用jquery增加每个元素的属性值(int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6996718/

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