리팩토링을 해보도록 하자.
😋꿀팁
똑같은 단어 선택해서 다같이 수정하고 싶을 때 그 단어 드래그 후 ctrl+d 하면 밑으로 쭉쭉 선택됨
만듬
🤔 : 이런 버튼을 1억개 씩이나 만들어야 한다면..?
(id를 1억개 씩이나 만들어서 일일이 수정해야 한다...)
😨
.
.
.
.
<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';
}
">
this
를 사용하면 문제 없다.
document.querySelector('#night_day2')
는 자기 자신을 가리키기 때문에 this
를 사용하면 된다. 태그의 id 또한 지워도 된다.
이렇게 하면 이 코드를 몇번이나 복붙해도 정상 작동함
코딩을 잘하는 법은 중복을 없애는 것이다!!!
위 코드에서 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';
}
">