HTML - action 屬性



HTML action 屬性用於 <form> 元素中,用於指定表單提交時應將表單資料傳送到哪裡。

此屬性值可以被表單標籤的 action 屬性覆蓋,這意味著如果我們使用 <input type = submit> 指定此屬性,當用戶提交表單時,它將根據表單標籤的 action 屬性源 URL 重定向,而不是根據 action 屬性。

“action” 屬性與 <form> 元素一起使用。當 <form> 元素中設定 method =dialog 屬性時,將忽略此屬性。

語法

<form action = "URL"></form>

應用於

下面列出的元素允許使用 HTML action 屬性。

元素 描述
<form> HTML <form> 標籤用於指定輸入欄位。

HTML action 屬性示例

以下是一些顯示 action 屬性的不同用法示例

帶有現有 URL 的 Action 屬性

在以下示例中,我們在 <form> 元素中使用 HTML “action” 屬性來定義表單提交時要執行的操作。以下程式碼將在網頁上生成一個包含輸入欄位和可點選按鈕的輸出。當用戶點選按鈕時,表單將成功提交。

<!DOCTYPE html>
<html lang="en">

<head>
   <title>HTML 'action' attribute</title>
   <style>
      form {
         width: 250px;
         padding: 10px;
         background-color: skyblue;
         border-radius: 10px;
      }

      input {
         padding: 10px;
         width: 200px;
      }

      button {
         padding: 10px;
         width: 100px;
         cursor: pointer;
      }
   </style>
</head>

<body>
   <!--HTML 'action' attribute-->
   <h3>HTML 'action' attribute</h3>
   <form action="welcome.html" method="GET">
      <h1>Login Page</h1>
      <input type="text" 
      placeholder="Username" 
      name="uname" 
      required>
      <br>
      <br>
      <input type="password"
         placeholder="Password" 
         name="password" 
         required>
      <br>
      <br>
      <button>Login</button>
   </form>
</body>

</html>

帶有錯誤 URL 的 Action 屬性

考慮另一種情況,我們將使用表單標籤的 action 屬性並分配錯誤的 URL,該 URL 在提交表單時顯示錯誤。以下程式碼將在網頁上生成一個包含輸入欄位和可點選按鈕的輸出。當用戶嘗試提交表單時,由於我們提供的 URL,它將顯示錯誤。

<!DOCTYPE html>
<html lang="en">

<head>
   <title>HTML 'action' attribute</title>
   <style>
      form {
         width: 330px;
         padding: 10px;
         background-color: skyblue;
         border-radius: 10px;
         color: white;
      }

      input {
         padding: 12px;
         width: 300px;
      }

      button {
         padding: 12px;
         width: 100px;
         cursor: pointer;
      }

      form h1 {
         text-align: center;
         font-family: sans-serif;
         letter-spacing: 2px;
      }
   </style>
</head>

<body>
   <!--HTML 'action' attribute-->
   <h3>Example of the HTML 'action' attribute</h3>
   <form action="/action_page.php" method="GET">
      <h1>Login</h1>
      <input type="text" 
         placeholder="Username" 
         name="uname" 
         required>
      <br>
      <br>
      <input type="password" 
      placeholder="Password" 
      name="password" 
      required>
      <br>
      <br>
      <button>Login</button>
   </form>
</body>

</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
action
html_attributes_reference.htm
廣告