Reasons and solutions for the failure of jQuery to add click events to dynamically added elements

1. Problem description

  After dynamically adding a piece of html code with jQuery's append() method, it is found that the new element cannot be obtained when the click event is bound to the newly added element.

Two, the solution

Elements are added using jQuery's on() method.

Official website definition and usage

Three: key code

$().ready(function(){

  $("#click1").bind("click",function(){

    $("p").append("<div class='new'><b>I'm clicked!</b></div>");

  });

  //on方法要先找到原选择器(p),再找到动态添加的选择器(.new)

  $("p").on("click",".new",function(){

    $(this).remove();

  });

});

 

Original blog: https://www.jb51.net/article/87287.htm

Guess you like

Origin blog.csdn.net/qq_44782585/article/details/113915341