I don’t know why this is not working.
When a li element is clicked I call a PHP file to get some results back and print them in my page. So far so good.
$("li").click(function(){
var item = $(this).html();
$.getJSON('fSearch.php',{sTerm: item}, function(data){
var results='';
$.each(data, function(i, item) {
results += "<li id='t'>"+item.Description+"</li>";
});
$('#ResultsHolder').html("<ul>"+results+"</ul>");
});
});
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?
Thanks in advance!
When you use a event shortcut (such as
click, orhover) 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.In the example below, I’ve used
#ResultsHolder.That should work for jQuery 1.7+. For an older version of jQuery, use
delegate()…Also, all the appended
lielements have theidof ‘t’. This will end up with invalid code as ids should be unique. Use a class instead if you want to have a group identifier.