Event handlers on dynamically created elements? [duplicate]

随声附和 提交于 2019-12-11 06:11:14

问题


$(document).ready(function () {

   $('.add-button').on('click', function () {
  
      $('.alert-button').after('<button type="button" class="alert-button">Click me! </button><br>');
  
  });
  

  $('.alert-button').on('click', function () {
  
    alert('HI!');
  
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button' class="alert-button">Click me! </button><br>
<button type="button" class="add-button">Add button!</button>

Hi! My " $('.alert-button').on('click'..." code works on elements created on page load, but not on dinamically created ones.

So i have a page with 2 buttons (please run the snippet above). If you click on "Click me!" alert "Hi!" appears.

But when I duplicate "Click me!" button via pressing "Add button", a click on the duplicated "Click me!" produces no alert "Hi!" (although it also has ".alert-button" class).

I want to see alert "Hi!" when I click on any "Click me!" button.

what am I doin' wrong?:)


回答1:


Just replace this function :

$(document).on('click','.alert-button', function () {

    alert('HI!');

});

This will also bind the click event on dynamically added element.




回答2:


The click handler is only bound to elements that already exist. You'll need to add handlers to elements as they're dynamically created. In your case, the best place to do that is in the .on function right after the new element is created.



来源:https://stackoverflow.com/questions/44552107/event-handlers-on-dynamically-created-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!