如何使用 JavaScript 動態停用按鈕元素?


在本文中,我們將學習如何使用 javascript 和“disabled”屬性動態停用 HTML 按鈕元素。

HTML 按鈕元素中的“disabled”屬性接受布林值(true 或 false),根據其值,它將停用按鈕並使其無法使用,即不可點選。我們可以透過將“disabled”屬性設定為“true”來停用 HTML 中的任何按鈕。

語法

<button disabled=”true”>Disabled Button</button>

讓我們透過一些示例來理解這一點:

示例 1

在這個例子中,我們將透過將“disabled”屬性傳遞為“true”來停用按鈕元素。

檔名:index.html

<html lang="en">
<head>
   <title>How to disable button element dynamically using JavaScript?</title>
</head>
<body>
   <h3>How to disable button element dynamically using JavaScript?</h3>
   <button id="btn" disabled="true">Disabled button</button>
</body>
</html> 

在這個例子中,我們將使用兩個單獨的按鈕動態停用和啟用 HTML 按鈕元素,分別用於啟用和停用按鈕。

檔名:index.html

<html lang="en">
<head>
   <title>How to disable button element dynamically using JavaScript?</title>
</head>
<body>
   <h3>How to disable button element dynamically using JavaScript?</h3>

   <button id="btn-p">Enabled button</button>
   <div style="display: flex; gap: 10px; margin-top: 10px;">
      <button id="enable">Enable</button>
      <button id="disable">Disable</button>
   </div>

   <script>
      const btn = document.getElementById("btn-p");
      const enableBtn = document.getElementById("enable");
      const disableBtn = document.getElementById("disable");

      enableBtn.addEventListener("click", () => {
         btn.disabled = false;
         btn.textContent = "Enabled button";
      });

      disableBtn.addEventListener("click", () => {
         btn.disabled = true;
         btn.textContent = "Disabled button";
      });
   </script>
</body>
</html>

示例 3

在這個例子中,我們將使頁面載入後經過一定時間(5 秒)後停用按鈕元素。我們可以使用 setTimeout() 函式將函式的執行延遲指定的時間(以毫秒為單位)。

檔名:index.html

<html lang="en">
<head>
   <title>How to disable button element dynamically using JavaScript?</title>
</head>
<body>
   <h3>How to disable button element dynamically using JavaScript?</h3>
   <button id="btn">Enabled button</button>

   <script>
      const btn = document.getElementById("btn");
      setTimeout(() => {
         btn.disabled = true;
         btn.textContent = "Disabled button";
      }, 5000);
   </script>
</body>
</html>

示例 4

在這個例子中,我們將提交表單時停用按鈕元素。我們可以使用 onsubmit 事件在提交表單時執行一個函式,然後在這個函式中停用按鈕。

檔名:index.html

<html lang="en">
<head>
   <title>How to disable button element dynamically using JavaScript?</title>
</head>
<body>
   <h3>How to disable button element dynamically using JavaScript?</h3>
   <form onsubmit="disableButton()">
      <input type="text" name="input" placeholder="Enter some text" />
      <button type="submit" id="btn">Submit</button>
   </form>
	  
   <script>
      function disableButton() {
	     const btn = document.getElementById("btn");
		 btn.disabled = true;
		 btn.textContent = "Disabled button";
	  }
   </script>
</body>
</html>

結論

在本文中,我們學習瞭如何使用 javascript 和 disabled 屬性動態停用 HTML 按鈕元素。我們可以透過將 disabled 屬性設定為 true、動態更改 disabled 屬性的值、使用 setTimeout() 函式延遲函式的執行或使用 onsubmit 事件在提交表單時執行函式來停用按鈕。

更新於:2023年8月2日

2K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.