javaScript/J Query & 스크립트
[javaScript] onclick function에서 this 가져오기
mooyou
2022. 12. 16. 23:35
728x90
300x250
SMALL
onclick를 사용해서 현재 클릭한 버튼에 이벤트를 주려면
<button type="button" onclick="this.innerHTML = 'Hello!'">Click</button>
이렇게 onclick에 인라인으로 넣었을 때는 클릭했을 때 Hello!라는 글자로 변경되는 걸 확인할 수 있다.
그런데 함수로 표시를 하려고 하면
<button type="button" onclick="call()">Click</button>
<script>
function call(){
this.innerHTML = 'Hello!'
}
</script>
동작을 안하는걸 확인할 수 있다. 함수를 사용해서 호출하는 경우 일반적으로 this는 global 객체인 window이기 때문이다.
이런 경우에는 함수를 호출할 때 첫 번째 인자로 this가 가리켜야 할 객체를 넘겨줘야 한다.
<button type="button" onclick="call(this)">Click</button>
<script>
function call(text){
text.innerHTML = 'Hello!'
}
</script>
728x90
반응형
LIST