I am trying for 2-3 hours on this script. It creates ul and append li to it. Then i try to attach eventListeners (click) which will be a trigger for some function. On my local try callback function only retrieves last li values. Is it a looping problem or jquery has any known issues with .on() ?
The Container ul tag below
<ul id="container">
<li>emtyp statically created</li>
</ul>
Here is js model js below:
var xy=1;
for(xy=1; xy<10; xy++){
$("#container").append('<li id="li_'+xy+'">'+xy+'</li>');
$("#li_"+xy).on("click",function(){alert(xy)});
}
You have to assign the event to the ul
itself, passing in the li
element as a parameter:
$('ul#container').on('click', '#li_' + xy, function() { ... });
This is known as event delegation.
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
If each li
element will have the same click
function, you can move that click handler outside of your for
loop completely.
As a side note you can also move that var
declaration down into your for
loop like so:
for (var xy = 1; ...; ...)