Can jQuery be applied in jQuery generated content?
I don't know why it doesn't work.
When the li element is clicked, I call the PHP file to return the results and print them on 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 on the li element everything works fine, I get the results. Now these results are another set of li and I want them to behave the same, but when I click on the generated li the function fails.
Why is this happening? Why doesn't jQuery recognize dynamically inserted li elements?
Thanks in advance!
source to share
When using an event shortcut (like click
or hover
), it will only work for events available to the DOM on page load. Since you are adding elements dynamically, you need to delegate an event listener to an element that is always available on your page.
In the example below, I have 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>");
});
});
This should work for jQuery 1.7+. For older version of jQuery use delegate()
...
$("#ResultsHolder").delegate("li", "click", function(){ ...
Also, all added items li
have id
of 't'. This will result in incorrect code, as the identifiers must be unique. Use a class instead if you want a group id.
source to share
When you call ("li"). click (), you bind events to existing li elements. When you create new li elements, you need to bind them to an event for the click to work.
So, change your loop to something like this ...
$.each(data, function(i, item) {
var li = $('li').text(item.Description);
$(li).click(function(e) { loadChildren(this); });
$("#ResultsHolder").append(li);
});
source to share
Use . delegate () :$(document).delegate("li","click",function(){...})
Or a newer version . on () $('li').on("click",function(){...})
If your li is in some fixed div, you can do it faster by replacing document
in the first snippet with that div's selector; and do the second$(SELECTOR).on("click","li",function(){...})
source to share