간단하게 만들어본 TODO리스트. 구현하려고 하는 것은 '완료'버튼을 누르면 해당 TODO리스트 카드의 배경이 회색으로 변경되는 것.
HTML코드
< body >
< h1 > 오늘 할 일 </ h1 >
< div class =" wrap ">
< div class =" todo__list ">
< h3 > 고양이 밥주기 </ h3 >
< p > 고양이 물, 사료 챙겨주기 </ p >
< button type =" button "> 완료 </ button >
</ div >
< div class =" todo__list ">
< h3 > 장보기 </ h3 >
< p > 토마토, 계란, 초코렛 사기 </ p >
< button type =" button "> 완료 </ button >
</ div >
< div class =" todo__list ">
< h3 > 코딩하기 </ h3 >
< p > 리엑트 강의 1주차 듣기 </ p >
< button type =" button "> 완료 </ button >
</ div >
< div class =" todo__list ">
< h3 > 짐정리하기 </ h3 >
< p > 옷, 책위주로 정리 </ p >
< button type =" button "> 완료 </ button >
</ div >
</ div >
</ body >
다음은 자바스크립트 코드를 직접 작성해 보았음.
const todoListArray = document . getElementsByClassName ( ' todo__list ' ) ;
const buttonArray = document . getElementsByTagName ( ' button ' ) ;
function done ( e ){
const array = e . target . id . split ( ' __ ' ) ;
todoListArray [ array [ 1 ]] . style . backgroundColor = ' grey ' ;
}
for ( let i = 0 ; i < todoListArray . length ; i ++ ) {
todoListArray [ i ] . setAttribute ( ' id ' , ` todo__ ${ i } ` ) ;
buttonArray [ i ] . setAttribute ( ' id ' , ` button__ ${ i } ` ) ;
}
for ( let i = 0 ; i < buttonArray . length ; i ++ ) {
buttonArray [ i ] . addEventListener ( ' click ' , done ) ;
}
버튼태그에 onclick속성으로 해당 카드의 배경을 바꾸는 방법을 생각했으나, 새로운 TODO리스트가 추가되면 onclick속성도 하나하나 다 작성해줘야 하는거아닌가?라는 생각에 자바스크립트 for문을 이용해서 추가된 TODO리스트에 각각 index역할을 하는 아이디를 알아서 부여해줘야겠다고 생각함.
새로 배운 점은 태그의 id속성 값을 가져오는 부분.
function done ( e ){
const array = e . target . id . split ( ' __ ' ) ;
todoListArray [ array [ 1 ]] . style . backgroundColor = ' grey ' ;
}
--.target.-- 을 통해서 속성 값을 읽어올 수 있었음.
다음은 이번 문제의 해설코드.
html 코드