event.target
실제 클릭된 요소
event.currentTarget
이벤트가 바인딩된 요소
아래의 버튼을 클릭했을 때,
<div class="container">
<button class="btn">버튼 클릭</button>
</div>
(JavaScript)
document.querySelector(".container").addEventListener("click", function (e) {
console.log("event.target:", e.target);
console.log("event.currentTarget:", e.currentTarget);
});
(출력결과)
event.target: <button class="btn">버튼 클릭</button>
event.currentTarget: <div class="container"></div>
=> event.target : 클릭된 가장 하위 요소를 반환
=> event.currentTarget : 클릭이벤트가( addEventListener 또는 onClick ) 적용된 요소를 반환.
태그에 인라인으로 onclick 적용한다면,
(1) 이벤트를 직접 태그에 할당하는 경우
<button onclick="handleClick(event)">클릭</button>
function handleClick(event) {
console.log(event.target); // <button>
console.log(event.currentTarget); // <button>
}
=> 둘 다 동일한 요소 반환.
(2) 이벤트 위임(Event Delegation) 이나 부모 요소에 이벤트를 등록하는 경우
<div onclick="handleClick(event)">
<button>클릭</button>
</div>
function handleClick(event) {
console.log(event.target); // <button>
console.log(event.currentTarget); // <div>
}
=> event.target : 클릭된 가장 하위 요소 반환.
=> event.currentTarget : 클릭이벤트 적용된 요소 반환.
'JavaScript > 공부공부' 카테고리의 다른 글
[JS] Form & Checkbox (2) | 2024.11.06 |
---|---|
[JS] Property vs Attribute (0) | 2024.11.06 |
[JS] addEventListener vs onclick (0) | 2024.11.06 |
[JS] new 연산자, 프로토타입 객체 (0) | 2024.11.05 |
[jQuery] jQuery 플러그인 $.fn (사용자 정의 함수) (0) | 2024.11.05 |