在 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>
输出
以上代码将产生以下输出 -
单击“单击此处”按钮后 -
广告