본문 바로가기

COA Lab's JS

자바스크립트 16 - 객체와 이벤트 연결하는 방법 4가지

이벤트 연결방식에는 크게 아래와 같이 4가지로 분류 해서 정리 할 수 있다. 

1. 인라인이벤트모델 : 태그요소에 바로 연결하는 방법

2. 기본이벤트모델 : 객체.onclick = function{}

3. IE이벤트모델 : 객체.atttchEvent('onclick', function(){});

4. 표준이벤트모델 : 객체.addEventListener('click', function(){});

 

현재, 기본이나 표준 방식으로 두로 사용하고 있다. 

 

아래는 이미지 태그의 이벤트의 종류(mousenter, mouseout)에 따라 src속성을 변경하는 코드이다. 

let img = document.querySelector('#imgChange');
img.onmouseenter = function(){
  //이미지의 src속성 값을 변경
  this.setAttribute('src', 'img/2.png');
}
img.onmouseout = function(){
  //이미지의 src속성을 원래값으로 변경
  this.setAttribute('src', 'img/1.png');
}
<h1>마우스 올리면 이미지변경</h1>

<img src="img/1.png" alt="이미지변경" id="imgChange" width="300"height="300">

아래는 자식요소를 선택하는 여러가지 방법이다. 

let list = document.querySelector('#list');//567
let btnLength = list.children.length-1;//2
console.log(btnLength);
let btnLast = list.children[btnLength];//마지막요소선택
let btnIndex1 = list.children[1];
btnLast.onclick = function(){
    console.log('마지막버튼을 클릭했습니다.');
}
btnIndex1.onclick =  function(){
    alert('버튼6을 클릭했습니다. ');
}
<div id="list">
    <input type="button" value="버튼5">
    <input type="button" value="버튼6">
    <input type="button" value="버튼7">
    <input type="button" value="버튼8">
    <input type="button" value="버튼9">
    <input type="button" value="버튼10">
</div>

 

위에서 보는 것처럼, div#list안의 input요소는 div의 자식들이다 

list.children으로 접근하고, 자식요소는 여러개 이므로 배열처럼 받는다. 

그래서 length속성이 있고, 배열처럼 받으므로 0부터 시작되는 [index순서]로 선택할 수 있다. 

객체를 선택하고, onclick르로 이벤트를 연결하였다.