본문 바로가기

프로그래밍/자바스크립트

[자바스크립트] 이벤트 : script에서 이벤트 연결

1. 선언적 함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>script에서 이벤트 연결</title>
<script type="text/javascript">
window.onload=function(){
    var header = document.getElementById('header');
    
    //선언적 함수
    function whenClick(){
        alert('CLICK');
    }
    
    //이벤트 연결            //이벤트 핸들러
    header.onclick = whenClick; 
    
    
    //이벤트 연결을 하는 것이 아니라 함수가 1회 호출되고 이벤트 발생 시 함수가 호출 되지 않음.
    //header.onclick = whenClick();
}
</script>
</head>
<body>
    <div id="header">클릭</div>
    
</body>
</html>
cs

 

2. 익명 함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>script에서 이벤트 연결</title>
<script type="text/javascript">
    window.onload = function(){
        var header = document.getElementById('header');
        
        //선언적함수보다 익명함수 사용하는게 더 간편하고 유용
        //이벤트 연결            이벤트 핸들러
        header.onclick = function(){
            alert('클릭');
        };
    };
</script>
</head>
<body>
    <div id="header">클릭</div>
</body>
</html>
cs