Can jQuery be applied in jQuery generated content?

jquery, json, php, sql

Solution

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.

In the example below, I've used `#ResultsHolder`.

$("#ResultsHolder").on("click", "li", 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>");
    });
});

That should work for jQuery 1.7+. For an older version of jQuery, use `delegate()`...

$("#ResultsHolder").delegate("li", "click", function(){ ...

Also, all the appended `li` elements have the `id` of '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.

Problem

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!

Original source