简体   繁体   中英

Javascript event triggering creating multiple button .on('click)

I'm using HTML slim for the code below.

.page
  .paper
    button.button.js-copier I copy things

- content_for :js_includes do
  javascript:
    var startingHtml = $('.page').html();

    function initializePlugin() {
      $('.js-copier').each(function () {
        $(this).on('click', function () {
          $('.page').append(startingHtml);
          $(document).trigger('page-refreshed');
        });
      });
    }

    // Run it right away
    initializePlugin();

    $(document).on('page-refreshed', initializePlugin);

Is there a way to fix the fact that when I click on the "I copy things" button, it creates multiple copies of the button as it is iterating over all the button from the button that was selected?

Also, is there a better way to write this code. All I'm trying to do is duplicate the button anytime I click on any buttons(first and any new button created buttons)

-Anthony

First change this:

  $('.js-copier').each(function () {
    $(this).on('click', function () {
      ...

to this:

  $('.page').on('click', '.js-copier', function () {
    ...

Read this to understand https://learn.jquery.com/events/event-delegation/#event-propagation

Then remove the 'page-refreshed' event because you don't need it:

   $(document).trigger('page-refreshed');
   ...
   $(document).on('page-refreshed', initializePlugin);

Demo solution:

 var startingHtml = $('.page').html(); function initializePlugin() { $('.page').on('click', '.js-copier', function () { $('.page').append(startingHtml); }); } // Run it right away initializePlugin(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="page"> <div class="paper"> <button class="button js-copier"> I copy things</button> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM