Skip to content Skip to sidebar Skip to footer

Javascript Buttons Returning Wrong Alert

I'm applying for a job and they threw a JS question detailed below: Write a function to render 10

Solution 1:

You should pass count to the function.

functioncreateBtn(count){
  var button = document.createElement("button");
  button.innerHTML = "Button " + count;
  var body = document.getElementsByTagName("body")[0];
  body.appendChild(button);
  button.addEventListener ("click", function() {
    alert('Button ' + count);
  });
}

functionbuttonRender(){
  for(var i = 0; i < 10; i++){
    createBtn(count);
    count++;
  }
}

https://jsfiddle.net/xw7mhag2/

Solution 2:

var count = 0;

  functioncreateBtn(count){
    var button = document.createElement("button");
    button.innerHTML = "Button " + count;
    var body = document.getElementsByTagName("body")[0];
    body.appendChild(button);
    button.addEventListener ("click", function() {
      alert("Button " + count);
    });
  }

  functionbuttonRender(){
    for(var i = 0; i < 10; i++){
    count++;
      createBtn(count);

    }
  }

  buttonRender();

Post a Comment for "Javascript Buttons Returning Wrong Alert"