JavaScript one() 事件处理链接导致奇怪的错误

JavaScript one() event handling chaining causes strange errors

我需要你的帮助。我目前正在编写一些代码来处理模态行为,例如单击按钮。对于一次捕获多个事件,我已经发布了这个问题:

那里说使用jQuery .one() 函数在打开弹出窗口并多次单击一个按钮时只捕获一次点击。这对一个按钮非常有用,但是当我使用两个按钮时,我又遇到了另一个错误。

首先,我更改了事件处理以接受多个事件:

jQuery(document).ready(function($) {
    $('button').click(function() {
        openConfirmationRemodal().one({
            confirmation: function() {
                console.log('Confirmation');
            },
            cancellation: function() {
                console.log('Cancellation');
            }
        });
    });
});

当我点击一个按钮时,我的弹出窗口打开时有两个按钮:

当我现在单击 Nein 按钮时,弹出窗口关闭并且控制台记录 Cancellation。当我现在再次打开弹出窗口并单击 Ja 按钮时,Confirmation 会记录两次。我真的不明白这个以及如何解决这个问题..

如果我以相反的方式执行此操作,错误是相同的,但顺序不同:

这里有一个工作示例。示例中的操作不知何故被触发了两次(最初)。这与我浏览器中的正常进度不同,但我认为这取决于代码段功能:

jQuery(document).ready(function($) {
  $('button').click(function() {
    openConfirmationRemodal().one({
      confirmation: function() {
        console.log('Confirmation');
      },
      cancellation: function() {
        console.log('Cancellation');
      }
    });
  });
});

function openConfirmationRemodal() {
  let remodal = $(`[data-remodal-id=test]`);

  remodal.remodal().open();

  return remodal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/remodal@1.1.1/src/remodal.js"></script>
<button>Open Pop-Up</button>
<div class="remodal" data-remodal-id="test">
  <button data-remodal-action="close" class="remodal-close"></button>
  <h1>Remodal</h1>
  <p>
    Responsive, lightweight, fast, synchronized with CSS animations, fully customizable modal window plugin with declarative configuration and hash tracking.
  </p>
  <br>
  <button data-remodal-action="cancel" class="remodal-cancel">Cancel</button>
  <button data-remodal-action="confirm" class="remodal-confirm">OK</button>
</div>

问题是因为您每次单击 'Open' 按钮时 re-bind 事件。要解决此问题,只需在页面加载时定义模态和事件一次,然后在单击按钮时在模态上调用 open() 。试试这个:

let $remodal = $(`[data-remodal-id=test]`);
let modal = $remodal.remodal();

$remodal.on({
  confirmation: function() {
    console.log('Confirmation');
  },
  cancellation: function() {
    console.log('Cancellation');
  }
});

jQuery($ => {
  $('button').click(function() {
    modal.open();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/remodal@1.1.1/src/remodal.js"></script>
<button>Open Pop-Up</button>
<div class="remodal" data-remodal-id="test">
  <button data-remodal-action="close" class="remodal-close"></button>
  <h1>Remodal</h1>
  <p>
    Responsive, lightweight, fast, synchronized with CSS animations, fully customizable modal window plugin with declarative configuration and hash tracking.
  </p>
  <br>
  <button data-remodal-action="cancel" class="remodal-cancel">Cancel</button>
  <button data-remodal-action="confirm" class="remodal-confirm">OK</button>
</div>