Language/Javascript
Event
Jinn
2023. 10. 26. 13:58
인라인 이벤트 모델
<html>
<head>
</head>
<body>
<button onclick="alert('이벤트 실행')">버튼</button>
</body>
</html>
HTML 태그 안에서 이벤트를 연결한다.
좀 더 깔끔한 코드를 위해서 script 태그에 함수를 만들고 함수를 호출해서 이벤트를 실행한다.
<html>
<head>
<script>
function buttonClick() {
alert('이벤트 실행');
}
</script>
</head>
<body>
<button onclick="buttonClick()">버튼</button>
</body>
</html>
고전 이벤트 모델
<html>
<head>
<script>
window.onload = function() {
const button = document.getElementById('button');
button.onclick = function() {
alert('이벤트 실행');
}
button.onclick = function() {
alert('이벤트 실행2');
}
}
</script>
</head>
<body>
<button id="button">버튼</button>
</body>
</html>
첫번째 이벤트는 실행되지 않고 마지막 이벤트만 실행된다.
표준 이벤트 모델
<html>
<head>
<script>
window.onload = function(event) {
alert('이벤트 실행');
}
</script>
</head>
<body>
</body>
</html>
이벤트 객체를 사용하여 이벤트 실행
이벤트 리스너(핸들러) 사용
<html>
<head>
<script>
window.onload = function() {
const button = document.getElementById('button');
button.addEventListener('click', () => {
alert('이벤트 실행');
})
button.addEventListener('click', () => {
alert('이벤트 실행2');
})
}
</script>
</head>
<body>
<button id="button">버튼</button>
</body>
</html>
이벤트가 차례대로 모두 실행된다.