이벤트
인라인방식
🔶개념 : 태그에 직접 정의한뒤, 이벤트 속성값으로 초기화
프로퍼티 방식
🔶개념 : 별도의 함수로 정의한뒤, 이벤트 속성값으로 초기화
인라인 VS 프로퍼티
🔶공통점
- 동일한 요소에 동일한 이벤트 타입 등록 불가능 ---> 마지막으로 사용한 코드가 처리된다
🔶차이점
- 함수대입시 순서상 함수를 먼저 처리하므로 프로퍼티 대입시 함수 소괄호 제거하여 실행
실습
버튼 클릭시 alert 띄우기
과정
◻ 1. 자바스크립트 html 태그및 id 에 이벤트 연결
<body class="w-80">
<div class="d-flex justify-content-center align-items-center vw-100 vh-100">
<div class="center-box d-flex flex-column justify-content-center align-items-center border border-3">
<button id="btn1" onclick="showAlert1()" class="btn btn-success mb-3">클릭(인라인방식1)</button>
<button id="btn2" class="btn btn-primary mb-3">클릭(프로퍼티방식1)</button>
<button id="btn3" class="btn btn-warning mb-3">클릭(프로퍼티방식2 addEventListener)</button>
</div>
</div>
</body>
![[Screenshot_441.png]]
◻ 2. 인라인방식
// 방식1 - 인라인방식
let showAlert1 = () => {
alert("클릭(인라인) 이벤트 발동")
}
![[Screenshot_442.png]]
◻ 2. 프로퍼티방식1
// 방식2
let btn2 = document.getElementById("btn2")
let showAlert2 = () => {
alert("프로퍼티 이벤트 발동")
}
btn2.onclick = showAlert2;
![[Screenshot_443.png]]
◻ 3. 프로퍼티방식2 (addEventListener)
// 방식3: addEventListener
const btn3 = document.getElementById('btn3')
btn3.addEventListener('click',()=>{
alert("Add evend listener")
})
![[Screenshot_444.png]]
전체코드
html
<body class="w-80">
<div class="wrap d-flex justify-content-center align-items-center vh-100 vw-100">
<div class="container d-flex flex-column justify-content-center align-items-center">
<div class="card border p-4">
<button class="btn btn-dark mb-3" onclick="show()">클릭</button>
<div id="p_event">마우스를 올려주세요</div>
<div id="p_event1">addEvent 확인</div>
</div>
</div>
</div>
</body>
js
// 방식1 - 인라인방식
let showAlert1 = () => {
alert("클릭(인라인) 이벤트 발동")
}
// 방식2
let btn2 = document.getElementById("btn2")
let showAlert2 = () => {
alert("프로퍼티 이벤트 발동")
}
btn2.onclick = showAlert2;
// 방식3: addEventListener
const btn3 = document.getElementById('btn3')
btn3.addEventListener('click',()=>{
alert("Add evend listener")
})
'➕ Language > ▹ Java Script' 카테고리의 다른 글
6. DOM (1) | 2025.05.23 |
---|---|
5. 객체 (2) | 2025.05.22 |
4. 함수 (0) | 2025.05.22 |
3. 반복문 (1) | 2025.05.21 |
2. 조건문 (1) | 2025.05.21 |