인생은 여행 人生は旅

WEB2 - JavaScript(조건문의 활용&리팩토링) 본문

코딩 공부

WEB2 - JavaScript(조건문의 활용&리팩토링)

하늘빛 칵테일 2024. 1. 11. 11:23
<body>
<h1><a href="index.html"></a>WEB</a></h1>
<input type="button" value="night" onclick="
document.querySelector('body').style.backgroundColor= 'black';
document.querySelector('body').style.color = 'white';
">

<input type="button" value="day" onclick="
document.querySelector('body').style.backgroundColor= 'white';
document.querySelector('body').style.color = 'black';
">

<input id= "night_day" type="button" value="night" onclick="
if (document.querySelector('#night_day').value === 'night'){
document.querySelector('body').style.backgroundColor= 'black';
document.querySelector('body').style.color = 'white';
document.querySelector('#night_day').value = 'day';
} else {

document.querySelector('body').style.backgroundColor= 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#night_day').value = 'night';
}
">
<body>
<h1><a href="index.html"></a>WEB</a></h1>

<input id= "night_day" type="button" value="night" onclick="
if (document.querySelector('#night_day').value === 'night'){
document.querySelector('body').style.backgroundColor= 'black';
document.querySelector('body').style.color = 'white';
document.querySelector('#night_day').value = 'day';
} else {

document.querySelector('body').style.backgroundColor= 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#night_day').value = 'night';
}
">

 

위 코드를 아래와 같이 줄여서 간소화시켰다 :0

 

리팩토링 - 우리가 만든 코드에서 비효율적인 코드를 제거하기.

 

</p>
<input id= "night_day2" type="button" value="night" onclick="
if (this.value === 'night'){
document.querySelector('body').style.backgroundColor= 'black';
document.querySelector('body').style.color = 'white';
document.querySelector('#night_day2').value = 'day';
} else {

document.querySelector('body').style.backgroundColor= 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#night_day2').value = 'night';
}
">
</body>
</html>

 

이 코드로 아랫쪽에도 낮, 밤 전환 버튼을 하나 더 생성.

<body>
<h1><a href="index.html"></a>WEB</a></h1>

<input id= "night_day" 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';
}
">
<ol>

 

var traget = document.querySelector('body') 를 넣어주면

target 만 쓰면 저 부분을 다 불러와준다.

this = 자기 자신을 가리킴

 

이런식으로 코드를 굉장히 간편하게 줄일 수 있었다 :)

굉장히 좋아보이긴하는데 잘 적용할 수 있을지 ㅎㅎ