在 JavaScript 中新增事件的最佳方法是什麼?


向任何元素新增事件的最佳方法是使用addEventListener()方法。

以下是JavaScript中新增事件的程式碼 -

示例

 實際演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result{
      font-size: 20px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Adding event in JavaScript</h1>
<div style="color: green;" class="result"<Hello world>/div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to increment the font size of above text
</h3>
<script>
   let resEle = document.querySelector(".result");
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.style.fontSize = "34px";
   });
</script>
</body>
</html>

輸出

以上程式碼將產生以下輸出 -

單擊“單擊此處”按鈕後 -

更新日期:2020-07-17

105 瀏覽量

開啟你的 職業生涯

透過完成課程,獲得認證

開始學習
廣告