본문 바로가기
카테고리 없음

[JavaScript] 여러 자식 태그를 포함하는 태그에 이벤트로 함수 호출하기

by happyhelen 2022. 2. 18.
<tbody>
         <tr>
            <td>사과</td>   
            <td>1,000<input type="number" min="0" max="10" value="0" id="apple" /></td><td id="apple">0</td>
         </tr>
         <tr>
            <td>딸기</td>   
            <td>2,000<input type="number" min="0" max="10" value="0" id="strawberry" /></td><td id="strawberry">0</td> 
         </tr>
         <tr>
            <td>참외</td>   
            <td>3,000<input type="number" min="0" max="10" value="0" id="melon" /></td>
            <td id="melon">0</td>
         </tr>
 </tbody>

 

 

위와같은 태그에서 id 가 apple, strawberry, melon 인 input 태그에서 number 을 변경했을 시 같은 동작을 주고자 할 때

 

아래와같이 코드를 불필요하게 반복하며 길이가 길어질 수 있다.

 

( 지금은 alert() 뿐이지만 긴 코드의 동작을 한다고 가정하자. )

 

 

 

 

굳이 id 마다 addEventListner() 을 넣어줄 필요없이,

 

동작이 일어난 태그를 파라미터(target)로 받아온 function 을 만들고,

 

id 들을 다 포함하는 태그(여기서는 tbl = document.querySelector("table#tbl") 이다) 에 addEventListner() 을 넣어줄 때

 

function 을 호출해주면 된다.

 

그리고 함수로 만들어두었기 때문에 다양한 event 동작들에 넣어줄 수도 있게 된다.

 

 

function func_calculate(target) { // target 은 동작이 일어난 태그(객체)를 받아온 것이다.
	...
}

...

tbl.addEventListener("keyup", function(e){func_calculate(e.target);}); 
// 키보드에서 손을 떼는순간 함수 호출, 이벤트가 발생된(키보드에서 손 뗀) 곳을 타켓으로 넘겨준다.
tbl.addEventListener("change", function(e){func_calculate(e.target);}); 
// 수량 변경이 발생한 그 태그를 타겟으로 넘겨준다.