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 theli
element as a parameter:This is known as event delegation.
If each
li
element will have the sameclick
function, you can move that click handler outside of yourfor
loop completely.As a side note you can also move that
var
declaration down into yourfor
loop like so: