Jquery events do not work on dynamically appended elements

前端 未结 2 1463
情深已故
情深已故 2020-12-14 10:43

I\'m trying to append new DOM objects to some Div and it works, but somehow - the events that I programmed for these new appended objects do not respond. Why is that?

<
相关标签:
2条回答
  • 2020-12-14 11:21
    $(document).ready(function(){
    
     $("#add").click(function(){
         $("#containerDiv").append("<p> I should hide as well if you click me </p>");
      });
    
     $("body").on("click","p", function(){
         $(this).hide();
      });
    
    });
    
    0 讨论(0)
  • 2020-12-14 11:35

    You need to use .on to handle events of dynamic elements.
    try this:

      $(document).on('click', 'p', function(){
         $(this).hide();
      });
    

    DEMO

    0 讨论(0)
提交回复
热议问题