如何使点击事件与动态生成的 html 元素一起工作

How to make click event work with dynamically generated html elements

当点击 add more link 时,会动态生成一个 div文本输入和 添加更多 link。这个动态插入的 add more link 不响应点击事件。尽管每个动态插入的 link 都有一个唯一的 id,并且点击事件使用 "delegated" 通过 Jquery on() 方法 绑定,但动态插入的link 在单击时添加更多字段不起作用。这是一个jsbin,整个代码如下:

Javascript:

<script type="text/javascript">
  $(document).on("ready", function(){

    return $(".add_people_filter").on("click", function(event){

      event.preventDefault();

      var time = new Date().getTime();
      var dynamicallyCreatedDiv = document.createElement("div");
      dynamicallyCreatedDiv.id = time;

      var peopleFilterContainerDiv = $("#people_filter_container");
      peopleFilterContainerDiv.append(dynamicallyCreatedDiv);
      var getHtmlForDynamicDiv = $(".people_filter").html();
      var theNewDiv = $(dynamicallyCreatedDiv);
      theNewDiv.append(getHtmlForDynamicDiv);

      var AddUniqueIdToLinK = time * 2;
      var x = time * 3;
      $(this).attr('id', AddUniqueIdToLinK);
      theNewDiv.find("a:last").attr('id', x);

      return theNewDiv;
   });
 });
</script>

html:

<div id="people_filter_container">
  <div class="people_filter"  >
    <input type="text" name="firstname" placeholder="add name" >
    <a href="#" data-behavior="add_people_filter" class="add_people_filter"> add more</a> 
    <br> <br>
  </div>

</div>

为此进行更改:

return $("body").on("click",".add_people_filter", function(event)
{
        ...... YOUR CODE      
});