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'; } }
using jquery
the event delegation can simple:
$('#output').on('click', 'li', makemered); function makemered() { $(this).css('background', 'red'); }
Comments
Post a Comment