Trying to click an item in a dynamically-generated list, but the $.click()
function just won't fire.
HTML for the list:
<div>
<ul id="site_list"> </ul>
</div>
jQuery to generate the list (which works as intended, generating a long list of data with the desired class attribute):
var sites =[];
$.getJSON("php/ABC.php", function(result){
$.each(result.Sites, function(i,v){
sites.push('<li class="site" id="site_'+ ABC + '</li>');
});
$('#site_list').append(sites.join(''));
});
jQuery to be triggered when clicking a list (doesn't work…it doesn't throw errors…just fails to respond. I've tried $('#site')
as well, to no avail. I suspect it's due to the method I'm using to generate the <ul>
…something is preventing the DOM from properly recognizing each element inside the UL.:
$('li').click(function(){
$(this).toggleClass("site_selected");
});
Best Answer
As you're addling
li
dynamically so you need delegate event handler toli
.Note
Delegate event structure of
.on()
is like following:Here
container
point to aStatic-element
that contains thetarget
element and belongs to DOM at page load.