JavaScript/생활코딩

웹브라우저 자바스크립트 - 프로퍼티 리스너

점미 2018. 11. 29. 16:21


프로퍼티 리스너 - https://opentutorials.org/course/1375/6760



프로퍼티 리스너 방식은 이벤트 대상에 해당하는 객체의 프로퍼티로 이벤트를 등록하는 방식이다.


아래의 방법이 프로퍼티 리스터 방식이다.


<input type="button" id="target" value="button" />

<script>

    var t = document.getElementById('target'); //객체의 프로퍼티를 가져온다.

    t.onclick = function(){ //t.onclick을 통해 이벤트를 등록한다.

        alert('Hello world'); //이벤트가 실행될 때 실행된다.

    }

</script>





이벤트 객체를 통하여 인자를 전달할 수 도 있다.

해당 코드는 ie8이하 버전에서 지원되지 않는다.


<!DOCTYPE html>

<html>

<body>

    <input type="button" id="target" value="button" />

<script>

    var t = document.getElementById('target');

    t.onclick = function(event){  //인자로 event를 준다.

        alert('Hello world, '+event.target.value); //이벤트가 실행 될 때 event.target을 통해 이벤트가 실행되는 대상의 value를 가져올 수 있다.

    }

</script>

</body>

</html>