Home > Web Front-end > JS Tutorial > Three ways to add events in Javascript

Three ways to add events in Javascript

autoload
Release: 2021-04-15 13:56:37
Original
2701 people have browsed it

Three ways to add events in Javascript

JavascriptThere 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(&#39;我被调用了&#39;)">按钮1</button>
</body>
</html>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template