event
객체에 속해있다.IE
에서는 target
, srcElement
로 사용되고, currentTarget
은 지원하지 않는다.일단, 예시를 보고 이 둘의 차이점을 비교해보자.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<tbody>
<div class="green" style="width: 300px; height: 300px; background-color: green;">
<div class="yellow" style="width: 200px; height: 200px; background-color: yellow;">
<div class="tomato" style="width: 100px; height: 100px; background-color: tomato;"></div>
</div>
</div>
</tbody>
</body>
</html>
const green = document.querySelector('.green');
green.addEventListener('click',function(e){
console.log("currentTarget : ",e.currentTarget);
console.log("Target : ",e.target);
});
현재 상황
과연 target
, currentTarget
의 결과가 어떻게 나왔을까 ?
결과
초록박스에 이벤트를 걸었다는 것을 명심해라.
👉🏻 초록박스 클릭시
👉🏻 노란박스 클릭시
👉🏻 주황박스 클릭시
currentTarget
: 이벤트가 걸려있는 요소를 가르킨다.
target
: 클릭한 요소를 가르킨다.
addEventListener 관련설명.
초록박스에 이벤트를 걸었는데 target
요소는
이벤트 버블링으로 인해 이벤트가 속해있는 요소에 전달( 이벤트 위임 ) 되기 때문에,
상위요소의 이벤트를 클릭하면 하위요소인 노란박스, 주황박스에게 위임받기 때문에 각각 하위요소의 이벤트를 걸어야 하는 상황에서 유용하게 사용할 수 있다.