简体   繁体   中英

Button to make boxes and add the counted numbers inside

I'm having trouble starting. I'm trying to make an 'add box' button that will add a new box to a container each time it is clicked. But I also need the number displayed inside of the box. For instance when I click it once, a box shows up as 1 and then the second box shows 2 etc. I'm not sure how to combine them in js.

To start with. Try this demo. https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick

Here a code is available which make add Hello World Text. Alter the code to create a box instead.

Since you didn't include any code, I can only guess. But I think you mean something like this:

 var boxes = 1; var addBox = function(){ document.getElementsByClassName("boxes")[0].innerHTML += "<div>Box " + boxes + "</div>"; boxes++; }; window.addEventListener("load", function(){ document.getElementsByClassName("addBox")[0].addEventListener("click", addBox); });
 <button class="addBox">Add Box</button> <hr> <div class="boxes"></div>


This code is just a quick-and-dirty example of how it could be done.
I'm basically just creating a counter variable and increment it on every execution of the addBox() function.

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