불로구

자바스크립트 - 이벤트 객체 본문

프로그래밍/JavaScript

자바스크립트 - 이벤트 객체

맹이맹이 2020. 6. 25. 00:12
반응형

이벤트 객체

- 이벤트가 발생하면, 브라우저는 발생한 이벤트에 관련된 다양한 정보를 담은 이벤트 객체를 만든다.

- 이렇게 만들어진 객체는 이벤트 리스너에 전달을 한다.

- 이벤트가 처리되면 이벤트 객체는 소멸된다.

이벤트 객체 전달받기

- 이름을 가진 이벤트 리스너 함수

- 익명 함수

- HTML 태그의 리스너

이 3가지의 방법으로 이벤트 객체를 전달받을 수 있다.

1) 이름을 가진 리스너 함수

- 첫 번째 매개변수를 통해 이벤트 객체를 전달받을 수 있다.

- 여기서는 매개변수 이름을 e로 사용하지만, 사용자가 마음대로 써도 된다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <h2>안녕하세요</h2>
        <hr>
    </div>
    <script>
        function f(e){
         alert(e.type);
        }
        document.getElementsByTagName("div")[0].onclick = f;
     </script>
</body>
</html>

마우스로 클릭하면 경고 창이 뜬다!

2) 익명 함수

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <h2>안녕하세요</h2>
        <hr>
    </div>
    <script>
        document.getElementsByTagName("div")[0].onclick = function(e){
            alert(e.type);
        };
     </script>
</body>
</html>

출력을 그대로지만 아까와 다르게 선언부 옆에 바로 함수를 선언했다!

3) HTML 태그의 리스너

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function f(e){
            alert(e.type);
        }
     </script>
</head>
<body>
    <div onclick="f(event)">
        <h2>안녕하세요</h2>
        <hr>
    </div>
</body>
</html>

event라는 이름으로 이벤트 객체를 전달받았다.

혹시나 궁금한 점은 댓글로 남겨주세요!

반응형
Comments