<h1>이벤트(Event) - this</h1>
<hr>
<p>이벤트 처리 함수에서 이벤트가 발생된 태그(Element 객체)를 표현하기 위해 this 키워드 사용</p>
<hr>
<div id="displayDiv">이벤트 처리</div>
<ul>
<li>메뉴-1</li>
<li>메뉴-2</li>
<li>메뉴-3</li>
</ul>
this로 객체를 표현해서 보다 간단하게 코드작성 가능.
document.getElementById("displayDiv").onclick=function() { //alert("태그에서 클릭 이벤트가 발생 되었습니다."); //Element 객체(태그)의 style 속성값 변경 - CSS 스타일 변경 //document.getElementById("displayDiv").style="color: green;"; //이벤트 발생 태그 : document.getElementById("displayDiv") >> this this.style="color: green;"; }var liList=document.getElementsByTagName("li");개별적인 온클릭 속성부여.
liList.item(0).onclick=function() { //liList.item(0).style="color: orange;"; this.style="color: orange;"; } liList.item(1).onclick=function() { //liList.item(1).style="color: orange;"; this.style="color: orange;"; } liList.item(2).onclick=function() { //liList.item(2).style="color: orange;"; this.style="color: orange;"; }for(i=0;i<liList.length;i++) {//i 변수에 [3]이 저장되면 반복문 종료 //반복문 내부에서 NodeList 객체에 저장된 모든 Element 객체에 이벤트 처리 함수 등록 // => 이벤트 처리 함수는 이벤트가 발생된 후 호출되어 실행 liList.item(i).onclick=function() { //이벤트 처리 명령은 반복문 종료 후 실행 //alert("i = "+i);//i = 3 //Element 객체가 없는 경우 객체 요소를 사용할 경우 에러 발생 //liList.item(i).style="color: orange;";//liList.item(3) >> null this.style="color: orange;"; ``` } }