gpt4 book ai didi

jquery - 如何使用jquery向元素添加渐进式ID?

转载 作者:行者123 更新时间:2023-12-01 06:41:27 26 4
gpt4 key购买 nike

使用jquery我想向一系列div添加一个id,但当然id需要始终不同,所以我想有一个渐进的数字,如id =“1”,id =“2”,id =“3”等

这是我的标记:

内容

    <div class="box">
<p>
content
</p>
</div>
<div class="box">
<p>
content
</p>
</div>
<div class="box">
<p>
content
</p>
</div>

我尝试了 .each() 循环,但我不知道要作为集合传递什么(可能是 $('.box').lenght()?但返回一个数字而不是集合)以及如何实现回调功能。有什么帮助吗?

提前致谢:)

毛罗

最佳答案

您可以使用.each()像这样:

$(".box").each(function(i, div) {
div.id = "div" + (i+1); //i starts at 0
});

ID 不能以数字开头,无论如何 HTML4 中都不行,所以我在上面添加了一个前缀。 .each()回调函数接收索引和元素作为参数,它是从 0 开始的,因此如果您希望它以 1 开头,请添加 1

You can test it out here .

关于jquery - 如何使用jquery向元素添加渐进式ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3295254/

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