So I tried the trusted google but found no satisfactory solution. Basically, I'm not sure if what I'm doing should开发者_StackOverflow社区 work.
I want to make an ajax call that returns a JSON result. I iterate over this result and write a string like this and push to #results span (all of this works fine):
var str='';
for (var n=0;n<data.length; n++){
str=+"<div class='game_name'>" + data[n]['name']+"</div><div class='game_id'>"+ data[n]['id'] +"</div>";
}
$('#results').html(str);
and then (by, then I mean that is coded into the page before results are returned) bind a click event using game_name class like this (this part doesn't work but works fine for something hand coded into the page at the beginning):
$(".game_name").bind('click',function(){
alert('here i am');
});
But the returned results don't have bind associated with it. How can I make it so that clicks are responded to? Is there a way to fire an event so that the DOM is made aware that new elements have been added to the DOM? or am I just missing how this should work?
thanks for any help
Use live()
instead of bind()
:
$(".game_name").live('click', function() {
alert('here i am');
});
Have you looked into jQuery's live
event? It will allow you to bind the click
for all dynamically added elements.
Use live instead:
$(".game_name").live('click',function(){
alert('here i am');
});
More info: http://docs.jquery.com/Events/live
If you make sure to run your binding after the $('#results').html(str);
line, your code should work, but i think you might be better off here, registering a live event listener, which says "all items that match this selector ever should be bound to this listener, even if they're added to the DOM at some point after this code is being executed":
$(".game_name").live('click',function(){
alert('here i am');
});
精彩评论