※ 자바스크립트에서 ' === ' 은 비교연산자로, boolean 데이터 타입이 출력된다
<script>
document.write(1===1); //-------------> True 출력
document.write(1===2); //-------------> False 출력
document.write(1<2); //-------------> True 출력
//HTML 에서는 '<'기호가 문법에 들어가므로 대소관계를 비교할 때, <(less than을 뜻함) 을 쓴다
</script>
※ 조건문 기본문법
if (조건) {
만약 조건(condition)이 참일 경우 실행할 코드
} else {
대신 실행할 다른 코드
}

조건문을 활용하여, 다음과 같이 나이트 모드, 주간 모드 변경되는 버튼을 만들었다.
<input id="mode" type="button" value="night" onclick="
if(document.querySelector('#mode').value === 'night'){ // id 값이 mode인 input 태그의 value 값이 night 이면
document.querySelector('body').style.backgroundColor = 'black'; // 배경은 검은색으로
document.querySelector('body').style.color = 'white'; // 텍스트는 흰색으로
document.querySelector('#mode').value = 'day'; // input 태그의 value 값을 day로 변경
} else {
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#mode').value = 'night';
}
">

마지막으로, 리팩토링(refactoring. 코드를 유지보수 편하게, 가독성 좋게 재조정하는 것)했다.
document.querySelector('#mode')은 자기 자신을 가리키는 코드라서 this를 쓰면 된다. 그러면 id도 쓸 필요가 없으므로 같이 지웠다.
여러 번 중복되고 있는 document.querySelector('body')는 변수 target에 저장해서 썼다.
(vscode에서 같은 코드 다중선택해서 수정할 때는 코드 드래그 한 뒤 Ctrl + Shift + L 누르면 된다)
<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';
}
">
'JavaScript' 카테고리의 다른 글
| 객체 (0) | 2023.03.01 |
|---|---|
| 함수 (0) | 2023.02.25 |
| 반복문 (2) | 2023.02.19 |
| 태그 선택 (0) | 2023.01.15 |
| HTML과 JS(script태그, 이벤트, 콘솔) (0) | 2023.01.14 |