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

Three ways to add events in Javascript

autoload
autoloadOriginal
2021-04-08 14:56:382703browse

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>

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!

Statement:
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