생활코딩/JavaScript

200804 3일차 정리

imname1am 2020. 8. 4. 23:16
반응형

제어할 태그 선택하기

1) <body> 선택

document.querySelector('body')

2) 자바스크립트 style.

(body 태그에 적을 때는 <body style="background-color:black;">)

document.querySelector('body').style.backgroundColor = "black";

비교 연산자와 Boolean 데이터 타입

 

1) === : 둘이 같나 비교

1 === 1    //  output : True

2) &lt ; less than (<)

1 &lt; 2    // 1 < 2 와 같은 의미

조건문의 활용

<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';
}
">

: value가 'night'일 때 클릭하면,

id가 'night_day'인 value를 'day'로 바꿈


리팩토링 (refactoring)

; 코드의 효율성 좋고, 읽기 좋게 개선

 

1) this 이용해 코드 간단히 작성 가능

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

2) target 변수 이용해 중복 코드 처리 가능

<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';
}
">

생활코딩 WEB2 JavaScript

반응형