JS eventListener disappears

I created a simple fidlle

var cnt = 1;
function add() {
    var root = document.getElementById('root')    
    root.innerHTML += '<br /><a id= "a_' +cnt + '" href="#">click</a>'
    var a = document.getElementById("a_"+cnt)
    a.addEventListener('click', function(event) {
        alert('click:a_'+cnt)
    })
    cnt++
}

When you click "Add" after adding a new link and after clicking on this link, a warning appears.

When more links with the Add button are added, only the last link works (others do not have a click event listener according to the devel tools).

Why does only the last link work and how can I make all links work?

+4
source share
4 answers

Since you are reinserting anchor tags in html. The question is similar Adding an HTML string to the DOM .

you can use

root.insertAdjacentHTML( 'beforeend', '<br /><a id= "a_' +cnt + '" href="#">click</a>');

instead

root.innerHTML += '<br /><a id= "a_' +cnt + '" href="#">click</a>'

Working fiddle https://jsfiddle.net/0nm4uLvd/

, , dom = > DOM , ? :)

+6

innerHTML . , "root" , .

. innerHTML ?.

+2

cnt. , add, , 1.

And write a semicolon after cnt ++

+1
source

You can set the class in your links: class = "some-class". Then you can use jquery to listen for the click event for elements of this class.

$(document).on('click', '.some-class', function(event) {
    alert('click:'+$(this).attr('id'));
});

Runnable example https://jsfiddle.net/2d99hq1h/1/

+1
source

Source: https://habr.com/ru/post/1663234/


All Articles