Javascript add events to newly created elements in a loop -


I have a loop that creates HTML links and assigns click events to them in the same loop. The click event only works for the last element which creates a loop.

  & lt; Div id = "list" & gt; & Lt; / Div & gt; & Lt; Script type = "text / javascript" & gt; User = {1: {id: 1}, 2: {id: 2}, 3: {id: 3}, 4: {id: 4}}; (Miscellaneous indices for users) {var user = user [index]; Document.getElementById ("list"). InnerHTML + '' & lt; A href = "" id = "user- '+ user.id +'" & gt; '+ User.id +' & lt; / A & gt; '; Var elements = document.querySelector ("#us-" + user.id); Console.log (element); Element.addEventListener ("click", function (event) {console.log (this); event.preventDefault ();}); } & Lt; / Script & gt;  

Here only the last link is click-able, however, if the links have already been created, then all event listeners will be working.

  & lt; Div id = "list" & gt; & Lt; A href = "#" id = "user-1" & gt; 1 & lt; / A & gt; & Lt; A href = "#" id = "user-2" & gt; 2 & lt; / A & gt; & Lt; A href = "#" id = "user-3" & gt; 3 & lt; / A & gt; & Lt; A href = "#" id = "user-4" & gt; 4 & lt; / A & gt; & Lt; / Div & gt; & Lt; Script type = "text / javascript" & gt; User = {1: {id: 1}, 2: {id: 2}, 3: {id: 3}, 4: {id: 4}}; (Miscellaneous indices for users) {var user = user [index]; Var elements = document.querySelector ("#us-" + user.id); Console.log (element); Element.addEventListener ("click", function (event) {console.log (this); event.preventDefault ();}); } & Lt; / Script & gt;  

It seems to work without any issue. Is it far enough to ensure that the element is linked to the element on creation?

Note: I do not want to use the JS framework for this. I know that this JQuery can be easily used.

  $ ("body") .on ('click', "# user-" + user.id, function () {});  

Note: The code I have posted is a simple code that I created on a fly, which clarifies the problem. I am using a template engine that returns a string, so I am using

  document.getElementById ("list"). InnerHTML + = '& lt; A href = "" id = "user - '+ user.id +'" & gt; '+ User.id +' & lt; / A & gt; ';  

Your problem is in . WinnerHTML that breaks the DOM with each iteration, which means that the previous events have been eliminated and you only have to listen to the last element connected. You can use the DOM API to create and add these elements and everything will work fine: jsfiddle.net/HtxZb

However, I would suggest using the event delegation. Without JQuery you can apply it like this:

  document.getElementById ('list') .addEventListener ('click', function (event) {var elem = event.target; console .log (do something with the link for example (elem.id) {} ​​* / event.preventDefault}});  

Comments