简体   繁体   中英

appending with jquery multiple div and each div has its unque ID

How to append multiple id's to show the different boxes. box2, box3 and box4. I was trying to use a for loop to add ascending numbers on the end of the wird box for the Id. 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.

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.

As of jQuery 1.8, you can create elements using the following syntax:

$("#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.

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


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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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