I made a small example to better exemplify, this way the event works normally:
let x = document.querySelector('#resposta');
x.innerHTML = '<a href="#" data-value="1" class="descricao-resposta" id="resposta-selecionada">teste</a><br/>';
var btnResponde = document.querySelector('#resposta-selecionada');
btnResponde.addEventListener('click', function(evento){
evento.preventDefault();
respondeExercicio();
});
function respondeExercicio(){
alert('ok');
}
Upshot: https://jsfiddle.net/uts27ejk/7/
Now I’m adding two buttons:
let x = document.querySelector('#resposta');
x.innerHTML = '<a href="#" data-value="1" class="descricao-resposta" id="resposta-selecionada">teste</a><br/>';
x.innerHTML += '<a href="#" data-value="1" class="descricao-resposta" id="resposta-selecionada">teste</a><br/>';
var btnResponde = document.querySelector('#resposta-selecionada');
btnResponde.addEventListener('click', function(evento){
evento.preventDefault();
respondeExercicio();
});
function respondeExercicio(){
alert('ok');
}
You can notice, that the second button does not work, this is because there cannot be two buttons with the same id, so it only assigns the event to the first button.
Upshot: https://jsfiddle.net/uts27ejk/9/
You can solve this way:
let x = document.querySelector('#resposta');
x.innerHTML = '<a href="#" data-value="1" class="descricao-resposta" >teste</a><br/>';
x.innerHTML += '<a href="#" data-value="1" class="descricao-resposta" >teste</a><br/>';
var elementos = document.querySelectorAll('.descricao-resposta');
[].forEach.call(elementos, function(elemento) {
elemento.addEventListener('click', function(evento){
evento.preventDefault();
respondeExercicio();
});
});
function respondeExercicio(){
alert('ok');
}
Upshot: https://jsfiddle.net/uts27ejk/18/
So you use only the class (since it can be repeated) makes a foreach to go through all the elements and assign the desired event.
You are creating more than one right button?
– Wictor Chaves
I’m actually only creating the A tag and trying to capture it after created with addEventeListener @Wictorchaves
– Francis Vagner da Luz
Remember that you cannot have 2 identical id’s in html, so if the code inside
if(xhr.status == 200){
Running twice won’t work as expected. Just as it is necessary to give extra behavior in relation to the click, to elements that are later added.– Isac
At what point do you add the event? Why not add it inside the
resposta.map
?– Felipe Marinho