javascript - Event doesnt work for elements putted via Ajax -


i have got elements event "onclick", need update elements ajax, unfortunately onclick event bound.

my question is, how refresh event trigger? there way it?

since event can bound elements exist @ time, use little trick called "event delegation".

that means going listen clicks on parent element exists, , if click on child meets requirement, something. example, newly added elements appended container:

<ul id="output"></ul> 

since did not mention using jquery, made version without it, , 1 it. example:


native js

document.getelementbyid('output').addeventlistener('click', makemered); 

then, in makemered example function, need check if element clicked on (event.target) meets requirements (i want <li> in case):

function makemered(event){     if(event.target && event.target.nodename == 'li'){         event.target.style.background = 'red';     } } 

js fiddle demo


using jquery

the event delegation can simple:

$('#output').on('click', 'li', makemered);  function makemered() {     $(this).css('background', 'red'); } 

js fiddle demo


Comments

Popular posts from this blog

node.js - How to mock a third-party api calls in the backend -

java - Could not locate OpenAL library -

Non Unique Username with ASP.Net Identity 2.0 -