create a link with dom and Numbering with "for", But this is messed up

This is my code, look at this.

function change(){
  for(a=0;a<1e4;a++){
    let aa = document.createElement('a');
    let bb = document.createTextNode("link " + a)
    let rot = aa.appendChild(bb)
    document.getElementById('div1').appendChild(rot);
  }
}
<div id="div1">
       <input type="submit" onclick="change()" value="Add New Link" class="btn btn-info">
</div>

But I want the user to create only one link each time they click and assign a regular number to each link.

But with one click, it creates 9999 links.

Please help me.

Upvotes: 0

Views: 41

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074595

If you don't want to create the links all at once, put a outside the function and give it an initial value, then use and increment a within the function:

let a = 0; // Start at 0
function change() {
    if (a < 1e4) {
        let aa = document.createElement("a");
        let bb = document.createTextNode("link " + a)
        let rot = aa.appendChild(bb)
        document.getElementById("div1").appendChild(rot);
        ++a; // Increment `a` for next time
    }
}

Upvotes: 1

Related Questions