리팩토링은 this, target 등의 변수를 이용해서 중복을 제거하는 방법이다.
1) this 이용
document.querySelector('#night_day2')
이 코드는 자기 자신을 가리키므로 this로 바꾸어주면 된다.
그리고 id="night_day2"는 더이상 사용하지 않으므로 지워준다.
<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';
}
">
2) target 이용
<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';
}
">
'Frontend' 카테고리의 다른 글
[JavaScript] Object (0) | 2022.08.05 |
---|---|
[JavaScript] 함수 (0) | 2022.08.02 |
[JavaScript] 비교 연산자 (0) | 2022.08.01 |
[JavaScript] 조건문 (0) | 2022.08.01 |
[JavaScript] 문법 (0) | 2022.07.28 |