[JavaScript] 06 Boolean, IF
Published:
In this post, 06 JavaScript lecture is introuduced.
Boolean Operator
JavaScript 의 Boolean Operator에는 다음이 있다.
<body>
<script>
document.write(1===1); // true 출력
document.write(1<2); // true 출력
</script>
1<2; <!-- 1<2 문구를 html에 출력하는 법 -->
</body>
Conditional Statements
조건문을 이용하여 다음과 같은 toggle 버튼을 만들 수 있다.
<body>
<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>
이 코드를 refactoring 해보자. onclick과 같은 event 안에서 실행되는 코드는 해당 코드가 속해 있는 tag를 가리키는 this 키워드를 사용할 수 있다. 이렇게 하면 같은 버튼 2개를 만들 때 각각의 id를 다르게 지정할 필요가 없어진다. 또한, 변수를 이용하여 반복을 줄일 수 있다.
<body>
<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';
}
">
</body>

Leave a Comment