简体   繁体   English

用jquery附加多个div,每个div都有其唯一的ID

[英]appending with jquery multiple div and each div has its unque ID

How to append multiple id's to show the different boxes. 如何附加多个ID以显示不同的框。 box2, box3 and box4. box2,box3和box4。 I was trying to use a for loop to add ascending numbers on the end of the wird box for the Id. 我试图使用for循环在ID的wird框的末尾添加升序数字。 Thank you for helping. 感谢您的帮助。

 $("#go").click(function(){ $("#boxContainer").append("<div id='box1'></div>"); }); 
 #box1 { width: 100px; height: 100px; background-color: blue; } #box2 { width: 100px; height: 100px; background-color: grey; } #box3 { width: 100px; height: 100px; background-color: orange; } #box4 { width: 100px; height: 100px; background-color: green; } 
 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script> <button id="go">click</button> <div id="boxContainer"> </div> </body> </html> 

You could set the id based on the number of children elements in the #boxContainer element. 您可以根据#boxContainer元素#boxContainer元素的数量来设置id

Use the .children() method to get the direct children elements, and then access the length property to get the number of element in the jQuery object. 使用.children()方法获取直接子元素,然后访问length属性以获取jQuery对象中元素的数量。

As of jQuery 1.8, you can create elements using the following syntax: 从jQuery 1.8开始,您可以使用以下语法创建元素:

$("#go").click(function() {
  var id = 'box' + ($("#boxContainer").children().length + 1);
  $("#boxContainer").append($("<div />", { id: id }));
});

Alternatively, you could also use the following: 或者,您也可以使用以下内容:

$("#go").click(function() {
  var id = 'box' + ($("#boxContainer").children().length + 1);
  $("#boxContainer").append('<div id="' + id + '"></div>');
});

Updated Example: 更新的示例:

 $("#go").click(function() { var id = 'box' + ($("#boxContainer").children().length + 1); $("#boxContainer").append($("<div />", { id: id })); }); 
 #box1 { width: 100px; height: 100px; background-color: blue; } #box2 { width: 100px; height: 100px; background-color: grey; } #box3 { width: 100px; height: 100px; background-color: orange; } #box4 { width: 100px; height: 100px; background-color: green; } 
 <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script> <button id="go">click</button> <div id="boxContainer"> </div> 

You can add a simple for loop, in this case will be 0-9. 您可以添加一个简单的for循环,在这种情况下将为0-9。

$("#go").click(function(){
     for (i = 0; i < 10; i++) {


    $("#boxContainer").append("<div id='box'" + i + "></div>");
}

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM