1

I am trying to create a function that will add buttons with their corresponding event listeners

var wordCount = 0;
function createButton(word, alert){
    document.querySelector('body').innerHTML += "<button id=\"word-" + wordCount + "\">" + word + "</button>";
    document.querySelector('#word-' + wordCount).addEventListener('click', function(){
        console.log(alert);
    })
    wordCount++;
}

createButton('a', 'A');
createButton('b', 'B');

Only the last button(b) responds. Clicking button(a) does not output anything. How would you fix this? Are there better ways that I could have implemented this?

1 Answers1

0

I am frequently facing this situation and doing it in a simpler way. see this, (the beauty of the method is if you start the variable full with single quotes, you can add any usual double quoted stuff within it, with ease and without any escaping issues). No addEventListener business needed here. :-)

var full = '';
var wordCount = 0;

function createButton(word, alert) {
    alert='\''  + alert + '\'';
  full = full + '<a href="javascript:void(0)" onclick="alert(' + alert + ');">'

  full = full + '<button id="word-' + wordCount + '" >' + word + '</button>';

  full = full + '</a>';

  document.querySelector('body').innerHTML += full;
  wordCount++;
}

function anyFunction(alert) {
  console.log(alert);
}

createButton('a', 'A');
createButton('b', 'B');
Padmanabhan
  • 152
  • 2
  • 14