JavaScript - 单击 HTML 按钮时创建警报

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/6 16:44:17

要单击按钮时触发警报,请使用 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 编辑器中选择选项"使用实时服务器打开"−

输出

输出如下 −

每当您按下按钮时,您都会收到一条警报消息。

输出

输出如下 −


相关文章


有用资源