본문 바로가기

JavaScript

[JavaScript] HTML 요소 안에서 inline 으로 이벤트 걸어줄 때 이벤트 객체 받아오기

 

<input type="checkbox" id="testInput" onchange="onChangeTestInput(event)" />
<input type="checkbox" id="testInput" onclick="onChangeTestInput(event)" />
<input type="checkbox" id="testInput" onkeydown="onChangeTestInput(event)" />



위처럼 onchange, onclick, onkeydown 등 html 요소 태그 안에 inline 으로 직접 콜백을 지정할 수 있다.

이때 event 객체를 파라미터로 받을 수 있다.
event 객체 안에는 isTrusted, currentTarget, type 등 이벤트와 관련된 다양한 정보들이 들어 있다.
inline 안에서는 event 라는 이름으로 정해져 있기 때문에 event 라는 이름으로 넣어줘야 한다.
호출받는 callback 함수에서는 로컬 scope 변수로 사용되기 때문에 이름은 아무렇게나 써도 되고 파라미터 위치만 맞춰주면 된다.

<script>
    function onChangeTestInput(e) {
        const isChecked = e.currentTarget.checked;
        if(isChecked) {
            console.log("체크되었습니다");
        } else {
            console.log("해제되었습니다");
        }
    }
</script>

 

 

- 241230

반응형