為什麼 formaction 屬性在
標籤外不起作用?


我們可以讓 formaction 屬性在 <form> 標籤外生效。formaction 屬性用於為一個表單指定多個提交 URL。當您提交表單時,Web 瀏覽器首先檢查 formaction 屬性。

如果不存在 formaction,Web 瀏覽器將繼續查詢表單元素中的 action 屬性。

示例

下面是一個 formaction 屬性的示例,其中帶有三個不同的提交按鈕 −

<!DOCTYPE html>
<html>
   <head>
      <title>HTML formaction attribute</title>
   </head>

   <body>
      <form method="post">
         <input type = "text" name="name"/><br>
         <button type = "submit" formaction = "btn1.php">Button1</button>
         <button type = "submit" formaction = "btn2.php">Button2</button>
         <button type = "submit" formaction = "btn3.php">Button3</button>
      </form>
   </body>
</html>

是的,formaction 屬性在表單元素外部不起作用,但您仍可以透過以下方式讓它們正常工作 −

示例

您可以使用關聯的表單 id 值輕鬆放置按鈕並在表單外部使用 formaction 屬性。

<!DOCTYPE html>
<html>
   <head>
      <title>HTML formaction attribute</title>
   </head>

   <body>
      <form method="post" id="newForm">
         <input type="text" name="name"/>
      </form>

      <button type="submit" formaction="btn1.php" form="newForm">Button1</button>
      <button type="submit" formaction="btn2.php" form="newForm">Button2</button>
      <button type="submit" formaction="btn3.php" form="newForm">Button3</button>
   </body>
</html>

更新於:2020 年 6 月 15 日

612 次瀏覽

啟動您的職業生涯

完成課程獲得認證

立即開始
廣告