Dynamically added HTML is not recognized by jQuery

Read some other things here: this is a similar problem, but I'm not sure how to apply this to my dilemma.

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

<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 that starts by pressing the LI button, for example:

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

It works fine until I dynamically change the html #mylist where the warning is empty.

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

+3
source share
2 answers

, $.on():

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

$.on(), http://api.jquery.com/on/.

+6

#mylist , li.

click, JQuery :

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

, live , , . , , #mylist.

. :

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

All Articles