'submit()' 方法会阻碍 'submit' 事件侦听器的执行吗?

Does 'submit()' method impede 'submit' event listener to be executed?

我觉得我在问“什么是 2+2?”但是我遇到了一个我不明白的问题......这是代码,很容易理解:

<button type="button" onclick="send()">
<form id="form">
  <input name="name">
</form>

<script>
  const form = document.getElementById("form");
  function send() {
    form.submit();
  }
  form.addEventListener("submit", (e)=>{
    // This code never gets executed,
    // the default behavior still works.
    // (note that my console preserves logs,
    // so it should be visible even though the page is being refreshed.)
    console.log("preventing default behavior");
    e.preventDefault();
  });
</script>

有人可以帮我解决这个问题吗?它应该很容易,但出于某种原因,今晚的代码不想对我很好。

这是(有点不直观的)预期行为。 HTMLFormElement.submit()the docs:

This method is similar, but not identical to, activating a form's submit . When invoking this method directly, however:

  • No submit event is raised. In particular, the form's onsubmit event handler is not run.

  • Constraint validation is not triggered.

The HTMLFormElement.requestSubmit() method is identical to activating a form's submit and does not have these differences.

因此,您可以使用 form.requestSubmit 而不是 form.submit

  const form = document.getElementById("form");
  function send() {
    form.submit();
  }
  form.addEventListener("submit", (e)=>{
    // This code never gets executed,
    // the default behavior still works.
    // (note that my console preserves logs,
    // so it should be visible even though the page is being refreshed.)
    
    e.preventDefault();
    console.log("preventing default behavior");
    send();
  });
<form id="form">
  <input name="name">
  <button type="submit" >submit</button>
</form>