单击提交 <button> 后访问事件处理程序中存在于 <form> 之外的 <form> 内容

Accessing <form> content in event handler after submit <button> is clicked that exists outside of <form>

可以在 <form> 元素之外添加一个 <button>,并使用 for 属性将其绑定到相关表单。我这样做是因为我想在按钮中包含一个 fontAwesome 图标,我不能用 <input> 这样做,因为 <input> 是一个空元素(没有结束标记)。但是,如果我想将事件处理程序绑定到表单提交事件,则无法识别该事件。这是为什么?按钮上的点击事件有效,但我无法访问表单数据。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"
      integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w=="
      crossorigin="anonymous"
    />
  </head>

  <body>
    <form id="form0">
      <input type="text" name="title" />
      <input type="text" name="id" />
    </form>
    <button type="submit" for="form0"><i class="fas fa-cart-plus"></i></button>
    <form id="form1">
      <input type="text" name="title" />
      <input type="text" name="id" />
    </form>
    <button type="submit" for="form1"><i class="fas fa-cart-plus"></i></button>
  </body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="js/test.js"></script>
</html>

//This works
$(document).on("click", "button", function (event) {
  console.log("running click event handler");
});

//This doesn't
$(document).on("submit", "form", function (event) {
  console.log(
    "running submit event handler, serilized data is: " + $(this).serialize()
  );
});

您可以使用 $(this).prev().serialize() 访问按钮上方的表单并获取该表单的值。

演示代码:

$(document).on("click", "button", function(event) {
  console.log("running click event handler");
  console.log(
    "running submit event handler, serilized data is: " + $(this).prev().serialize()
  );
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Document</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />
</head>

<body>
  <form id="form0">
    <input type="text" name="title" />
    <input type="text" name="id" />
  </form>
  <button type="submit" for="form0"><i class="fas fa-cart-plus"></i></button>
  <form id="form1">
    <input type="text" name="title" />
    <input type="text" name="id" />
  </form>
  <button type="submit" for="form1"><i class="fas fa-cart-plus"></i></button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</html>