views:

164

answers:

2

Read some other things on here re: this similar problem but am not sure how to apply this to my dilemma.

I have a jquery function that replaces some HTML in a list.. For example, before the function runs:

<ul id="mylist">
<li id="item1">blah blah blah</li>
<li id="item2">blah blah blah</li>
<li id="item3">blah blah blah</li>
</ul>

Then I have another which runs on click of the LI e.g:

$("#mylist li").click(function () {
alert($(this).attr("id"));
});

Works fine until I dynamically modify the #mylist html, where the alert is blank.

How can I replace the #mylist html and still be able to select the li's found within?

+4  A: 

To maintain this functionality on all future dynamically-added li's, you will need to use $.live();

$("#mylist li").live("click", function() {
  alert($(this).attr("id"));
});

Read more at http://docs.jquery.com/Events/live

Jonathan Sampson
Thanks so much, this works perfectly.
Jeff
You're welcome, Jeff. Keep up the good work!
Jonathan Sampson
+1 Thanks for the link
Senthil
+1  A: 

When you replace the contents of #mylist you also remove any event handles that were previously attached to its child li elements.

Instead of the normal click function, try using jQuery's live function:

$("#mylist li").live("click", function() {
    alert($(this).attr("id"));
});

Please note that live events work a bit differently than traditional event, especially when it comes to bubbling and event canceling. If this is a problem, then make sure you reattach click events after you manipulate #mylist.

You might also consider using event delegation. Here's a quick example:

$("#mylist").click(function(e) {
    alert($(e.target).closest("li").attr("id"));
});
Xavi