Home >Web Front-end >JS Tutorial >Three ways to add events in Javascript
Javascript
There are many ways to add events. This article mainly lists three ways to add events, including adding to element event attributes, adding to Javascript
In script, event listener.
1. Add to the element event attribute
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>php.cn</title> </head> <body> <button onclick="alert('我被调用了')">按钮1</button> </body> </html>
2. Add to the JS script
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>php.cn</title> </head> <body> <button onclick="">按钮2</button> <script> const btn2=document.querySelector("button"); btn2.onclick=function(){ alert("你好"); } </script> </body> </html>
3. Event listener
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>php.cn</title> </head> <body> <button onclick="">按钮3</button> <script> const btn3=document.querySelector("button"); btn3.addEventListener("click",function(){ alert("被调用了"); }); </script> </body> </html>
Recommended: "2021 js interview questions and answers (large summary) 》
The above is the detailed content of Three ways to add events in Javascript. For more information, please follow other related articles on the PHP Chinese website!