jQuery 迭代具有相同 ID 的 div 并添加数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11480365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:39:14  来源:igfitidea点击:

Iterating over divs with same ID and adding number

jqueryloops

提问by gregorvand

I am trying to iterate over every div with the the id 'slide' and add a number to the end (e.g slide1, slide2, etc)

我正在尝试使用 id 'slide' 遍历每个 div 并在末尾添加一个数字(例如 slide1、slide2 等)

I have been able to have a series of classes added to each div, but I can only get the same code to rename the first slide, not the rest of them.

我已经能够将一系列类添加到每个 div,但我只能获得相同的代码来重命名第一张幻灯片,而不是其余的。

$(document).ready(function() {
 $("#slide").each(function(i) {
    $(this).attr('id', "slide" + (i + 1));
 });
});?

and jsfiddle here http://jsfiddle.net/YsvCe/1/

和 jsfiddle 在这里http://jsfiddle.net/YsvCe/1/

Thanks in advance

提前致谢

回答by grc

You should use classes rather than ids for multiple elements.

对于多个元素,您应该使用类而不是 id。

<div class="slide">hello</div>

...

$(document).ready(function() {
    $(".slide").each(function(i) {
        $(this).attr('id', "slide" + (i + 1));
    });
});?

Example: http://jsfiddle.net/QaB76/

示例:http: //jsfiddle.net/QaB76/

回答by undefined

ID attributes must be unique, idselector as it should, only returns the first matched element:

ID 属性必须是唯一的,id选择器应该只返回第一个匹配的元素:

$(document).ready(function() { 
    $("div[id^='slid']").attr('id', function(i) {
       return "slide" + ++i;
    });
});

DEMO

演示

回答by sachleen

Elements must have a unique ID. the eachfunction isn't iterating over the other divs. So find a way to select them all without violating that rule. The following works:

元素必须有唯一的 ID。该each函数不会迭代其他 div。因此,找到一种在不违反该规则的情况下将它们全部选中的方法。以下工作:

$("div").each(function(i)