Skip to content Skip to sidebar Skip to footer

Dynamically Added Html Not Being Recognized By Jquery

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, b

Solution 1:

To maintain this functionality on all future dynamically-added list items, you should use event delegation with $.on():

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

Read more about $.on(), online at http://api.jquery.com/on/.

Solution 2:

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"));
});

Post a Comment for "Dynamically Added Html Not Being Recognized By Jquery"