0

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)});
}

http://jsfiddle.net/caglaror/c8jg6f8y/1/

caglaror
  • 459
  • 1
  • 13
  • 28

1 Answers1

3

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; ...; ...)
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • After reading whole night over my question, i got the point. Whenever a user actions includes inserting or removing elements from the working area we should use `event delegation`. But if we are using such thing like ajax to reload all ingredients of container element, we can use closure. In my real application situation, i am reloading data with json and then recreating inner elements (li). So i am going to use closure variables. @Arun and @James you are great guys ;) – caglaror Aug 14 '14 at 06:44