为什么这个表格被提交了两次?

Why is it that this form is being submitted twice?

我试图理解为什么在执行以下步骤后多次提交以下代码段中的表单:

  1. 单击其中一个提交按钮。将出现确认 div
  2. 点击确认中的Cancel按钮。
  3. 现在点击另一个提交按钮。
  4. 点击确认中的Yes按钮。
  5. 控制台日志显示表单提交处理程序被触发了两次。

谁能帮我看看how/why这是怎么回事,这样我就可以防止多次提交?

const $form = $("#form-test");
const $confirm = $("#confirm");

$form.on("submit", function (e, $btn) {
    e.preventDefault();
    console.log("Submitting!", $btn);
});

$confirm.find("button").on("click", function () {
    $confirm.hide();
});

$form.find("button").on("click", function (e) {
    const $btn = $(this);

    $("#btn-yes").one("click", function () {
        $form.trigger("submit", $btn);
    });

    $("#btn-cancel").one("click", function () {
        console.log("Cancelled!", this);
    });

    $confirm.show();
});
#form-container, #confirm {
  border: 1px solid #000;
  padding: 10px;
}

#confirm {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="confirm">
    Are you sure?
    <button id="btn-cancel" type="button">Cancel</button>
    <button id="btn-yes" type="button">Yes</button>
</div>

<div id="form-container">
    <form id="form-test">
        <input type="text" name="test" value="Foo">
        <button type="button">Submit 1</button>
        <button type="button">Submit 2</button>
    </form>
</div>

你是运行以下的人:

$("#btn-yes").one("click", function () {
    $form.trigger("submit", $btn);
});

$form.find("button").on("click" 处理程序中。如果您点击按钮两次,您将添加两次处理程序。

要么在添加新处理程序之前删除之前的处理程序,要么在外部添加 yes/cancel 处理程序(无需将它们添加到点击处理程序中)。

const $form = $("#form-test");
const $confirm = $("#confirm");

$form.on("submit", function(e) {
  e.preventDefault();
  console.log("Submitting!");
});

$confirm.find("button").on("click", function() {
  $confirm.hide();
});

$("#btn-yes").one("click", function() {
  $form.trigger("submit");
});
$("#btn-cancel").one("click", function() {
  console.log("Cancelled!", this);
});
$form.find("button").on("click", function() {
  $confirm.show();
});
#form-container,
#confirm {
  border: 1px solid #000;
  padding: 10px;
}

#confirm {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="confirm">
  Are you sure?
  <button id="btn-cancel" type="button">Cancel</button>
  <button id="btn-yes" type="button">Yes</button>
</div>

<div id="form-container">
  <form id="form-test">
    <input type="text" name="test" value="Foo">
    <button type="button">Submit 1</button>
    <button type="button">Submit 2</button>
  </form>
</div>