The first time I click to a li element all works fine, I get results. Now these results is another set of li's and I want them to behave the same, but when I click on the generated li's the function is not executed..

Why is this happening? Why jQuery does not recognize the dynamically inserted li elements?

6 Answers
6

When you use a event shortcut (such as click, or hover) it will only work for events which are available to the DOM on page load. As you are appending elements dynamically you need to delegate the event listener to an element which is always available in your page.

.click() is not a live handler, is only binds the event to elements that exist in the DOM at the time of execution. If you want the events to be live, you'll need to look into another handler, such as .on()

if you use live(), be sure to call that on your parent element like this... $("ul").on('click', 'li', function(e) { ... this will not work... $("li").on('click', function(e) { ...
–
TrentApr 10 '12 at 13:49

If your li's are in some fixed div, you can make it faster by replacing document in the first snippet with the selector of that div; and make the second one $(SELECTOR).on("click","li",function(){...})