JavaScript - 單擊 HTML 按鈕時建立警報


要針對按鈕點選觸發警報,請使用 addEventListener()。假定下面是我們 HTML 網頁上的按鈕 −

<button type="button">Please Press Me</button>

示例

以下是程式碼 −

 現場演示

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <button type="button">Please Press Me</button>
</body>
<script>
   var pressedButton = document.getElementsByTagName("button")[0];
   pressedButton.addEventListener("click", function (event) {
      alert("You have pressed the button..........")
   })
</script>
</html>

要執行上述程式,請將檔案命名為 anyName.html(index.html)。右鍵單擊該檔案,然後在 VS Code 編輯器中選擇選項“透過即時伺服器開啟” −

輸出

輸出如下 −

只要按下按鈕,就會收到警報訊息。

輸出

輸出如下 −

更新時間:2020 年 10 月 3 日

4K+ 檢視

開啟您的職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.