使用 jquery 动态创建具有递增 id 的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7926484/
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-27 00:27:51  来源:igfitidea点击:

Dynamically create divs with incremented id using jquery

jquery-uijqueryjquery-selectors

提问by subho das

I have a text I want to append multiple divs but the id should be changed dynamically. e.g:

我有一个文本,我想附加多个 div,但 id 应该动态更改。例如:

<div id=first>text</div>
<div id=first0>text</div>
<div id=first1>text</div>
<div id=first2>text</div>
<div id=first3>text</div>
<div id=first4>text</div>
<div id=first5>text</div>

Any help? thanks..

有什么帮助吗?谢谢..

回答by Hailwood

Your title and question content seem to disagree with each other. I am assuming you are wanting to create div's where each id sequentially increments each time one is created?

您的标题和问题内容似乎不一致。我假设您想要创建 div,其中每个 id 在每次创建时顺序递增?

$(function(){
  var count = 0;
  $('#append').click(function(){
    $('#parent').append('<div id="first'+count+'">text</div>');
    count++;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="append">Add DIV</a>
<div id="parent"></div>

回答by PiTheNumber

You can change it with .attr():

您可以使用.attr()更改它:

$('#first').attr('id', 'first6')

回答by Ben

try to change the code to :

尝试将代码更改为:

<div id="first">text</div>
<div id="first0">text</div>
<div id="first1">text</div>
<div id="first2">text</div>
<div id="first3">text</div>
<div id="first4">text</div>
<div id="first5">text</div>

dont forget the idinside " " (id="first"not id=first)

不要忘记id里面的“”(id="first"不是id=first

now you can simply use jquery : $("#first").attr('id','first6');

现在你可以简单地使用 jquery : $("#first").attr('id','first6');

回答by Jghorton14

If you were interested in how styling works.`

如果您对样式的工作方式感兴趣。`

$(function(){
  for (let i = 0 ;i < 10; i ++){  
      $('#foo').append('<div id="first'+i+'">text</div>');
  }
});
#first4 {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo"></div>

回答by Jitendra Singh Jeena

Create a div with id=Container and the create 5 divs dynamically using following code

创建一个 id=Container 的 div 并使用以下代码动态创建 5 个 div

//using JavaScript
 for(var i=0;i<5;i++){
     var obj = document.getElementById("container");
     obj.innerHTML += '<div id="first'+i+'"></div>';
 }