코딩성장스토리

javascript 두번째 도전기 본문

프론트 엔드/javascript

javascript 두번째 도전기

까르르꿍꿍 2021. 9. 18. 15:55

리팩토링 중복의 제거

똑같은 코드를 여러개 적어야만 할때 이름을 다르게 해야하므로 id나 class를 꾸준히 바꿔줘야한다 이걸 방지하기 위해 this가 존재한다.

<input id="nightday" type="button" value="night" onclick="

if(document.querySelector('#nightday').value==='night'){

document.querySelector('body').style.backgroundColor='black';

document.querySelector('body').style.color='white';

document.querySelector('#nightday').value='day';

}else{

document.querySelector('body').style.backgroundColor='white';

document.querySelector('body').style.color='black';

document.querySelector('#nightday').value='night';

}

">

아래는 this를 이용해서 쓴코드

<input type="button" value="night" onclick="

if(this.value==='night'){

document.querySelector('body').style.backgroundColor='black';

document.querySelector('body').style.color='white';

this.value='day';

}else{

document.querySelector('body').style.backgroundColor='white';

document.querySelector('body').style.color='black';

this.value='night';

}

">

그리고 여기서document.querySelector('body') 이 문구가 중복되는 것이 보인다.

이 중복을 없애기 위해서 변수var을 이용하면 간결해진다

예를 들어

<input type="button" value="night" onclick="

var target =document.querySelector('body');

if(this.value==='night'){

target.style.backgroundColor='black';

target.style.color='white';

this.value='day';

}else{

target.style.backgroundColor='white';

target.style.color='black';

this.value='night';

}

">

배열과 반복문

배별 만드는법

<script>

var 변수이름=[, , , , ,];

</script>

이렇게 반복문과 배열을 이용하면

예시로

<input type="button" value="night" onclick="

var target =document.querySelector('body');

if(this.value==='night'){

target.style.backgroundColor='black';

target.style.color='white';

this.value='day';

var alist= document.querySelectorAll('a');

var i=0;

while(i<alist.length){

alist[i].style.color='powderblue';

i=i+1;

}

}else{

target.style.backgroundColor='white';

target.style.color='black';

this.value='night';

var alist= document.querySelectorAll('a');

var i=0;

while(i<alist.length){

alist[i].style.color='blue';

i=i+1;

}

}

">

이런 응용이 가능하다.

'프론트 엔드 > javascript' 카테고리의 다른 글

javascript 세번째 도전  (0) 2021.09.18
javascript 도전기  (0) 2021.09.18