2022-08-14 JS_3

2022. 8. 16. 00:23FE/JavaScript

 

8.15 광복절

 


 

 

 

변수와 대입 연산자 - 생활코딩

변수와 대입 연산자 2017-12-01 03:26:24

opentutorials.org

 

이 글은 이고잉님의 오픈튜토리 강의를 듣고 정리한 내용입니다.

 


JS 학습의 방향성

 

이미 파이썬, C, Java를 배웠다.

 

이 짬(?)을 바탕으로 빠르게 JavaScript를 배워보겠다?

 

배경지식을 바탕으로 부족하거나 새로운 지식만 짚고 넘어갈 것이다.

 


제어할 태그 선택하기

 

 

버튼 2개를 생성했다.

 

night 버튼을 누르면 배경은 어둡게, 글자는 밝게 만들고 싶다.

 

또 day는 그 반대로 기능하도록 만들고 싶다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        h1{
            color : black;
            text-decoration : none;
        }
    </style>
</head>
<body>
    <h1>WEB</h1>
    <input type="button" value="night" >
    <input type="button" value="day" >
</body>
</html>

Html 코드다.

 

<input type="button" value="night" onclick="">
<input type="button" value="day" onclick="">

input 태그에 onclick 속성을 추가한다.

 

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

클릭 이벤트가 발생한 경우 실행할 JavaScript 코드를 추가한다.

 

설명은 아래에.

 


document.querySelector()

 

배경 색상을 변경하기 위해서는 body 태그의 color를 변경해야 한다.

 

body 태그를 상호작용의 대상으로 지정한다.

 

검색창에 대충 “JavaScript choose tag”라고만 입력해도 알아낼 수 있다.

 

 

Document.querySelector() - Web API | MDN

Document.querySelector()는 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Element를 반환합니다. 일치하는 요소가 없으면 null을 반환합니다.

developer.mozilla.org

 

<!-- tag -->
document.querySelector('body') 

<!-- class -->
document.querySelector('.class') 

<!-- id -->
document.querySelector('#id') 

 


document.querySelectorAll()

 

document.querySelectorAll('a');

웹 페이지의 모든 a태그를 노드 리스트로 반환.

 

노드 리스트란?

 

NodeList 객체는 일반적으로 element.childNodes와 같은 속성(property)과 document.querySelectorAll와 같은 메서드에 의해 반환되는 노드의 콜렉션입니다.

 

var alist = document.querySelectorAll('a');
console.log(alist[0]);
console.log(alist[1]);
console.log(alist.length);

 

얼핏 보면 배열과 사용법이 비슷하다. (그래도 완벽히 같지는 않으니 주의할 것.)

 

 


배경 색상 바꾸기

 

배경 색상을 바꾸는 구채적인 방법은 대충 “JavaScript change backgroundcolor”라고 검색한다.

 

 

HTML DOM Style backgroundColor Property

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

대충 w3schools.com에서 가르쳐준다.

 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      h1 {
        color: black;
        text-decoration: none;
      }
    </style>
  </head>
  <body>
    <h1>WEB</h1>
    <input
      type="button"
      value="night"
      onclick="
    document.querySelector('body').style.backgroundColor = 'gray';
    document.querySelector('body').style.color = 'white' ;
"
    />
    <input
      type="button"
      value="day"
      onclick="
    document.querySelector('body').style.backgroundColor = 'white';
    document.querySelector('body').style.color = 'black' ;
"
    />
    <p>
        hello world~
    </p>
  </body>
</html>

 

 


변수 선언

 

var name = 'Tired_I' ;

var 없어도 되지만 붙이라네용? (이유는 아직 모름;;)

 


조건문

 

JavaScript의 조건문 문법이다.

 

if (조건1) {...}
else if (조건2) {...}
else {...}

(참고 : https://www.w3schools.com/js/js_if_else.asp)

 

특이한 점은 다른 언어(C, Java)와 비교 연산자가 다르다.

 

JS에선 ===으로 ‘=’을 3번 붙여 사용한다.

 


실습 : 토글

 

일전에 만든 day, night 버튼을 하나의 토글 버튼으로 합쳐보자.

 

...
    <body>
    <h1>WEB</h1>
    <input id="night_day" type="button" value="night" onclick="
    if(document.querySelector('#night_day').value==='night'){
        document.querySelector('body').style.backgroundColor = 'gray';
        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';
    }
    "/>

    <p>
        hello world~
    </p>
  </body>
...

 

 

if(document.querySelector('#night_day').value==='night'){…} : 해당 태그의 value값에 따라서 가려서 실행한다.

 

위 코드에서 아쉬운 부분은 토글 기능을 구현하기 위해 굳이 id=”night_day”라는 속성을 추가한 것이다.

 

리팩터링에 대하여 배우며 개선해보자.

 


리팩터링

 

리팩터링(refactoring)은 코드의 가독성을 높이고, 유지보수를 편하게 만들고, 중복된 코드를 줄이는 방향으로 대충 더 좋은 코드로 개선하는 작업을 뜻한다.

 

방금 전에 아쉬웠던 부분을 리팩터링 해보자.

 


this 사용

 

<input type="button" value="night" onclick="
    if(this.value==='night'){
        document.querySelector('body').style.backgroundColor = 'gray';
        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를 사용한다.

 

그러면 id = “night_day”document.querySelector('#night_day') 없이 동일한 기능을 구현할 수 있다.

 

또한 가독성과 유지보수에 이점이 생긴다.

 


변수 사용

 

중복되는 부분을 최소화하기 위해서 변수를 사용할 수 있다.

 

많은 중복이 발생하는 document.querySelector(’body’)를 변수에 넣는다.

 

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

 

이렇게 바뀌면 변수 target의 값을 바꾸면 전체의 값을 바꾸는 기적을 목도할 수 있을 것!

 


'FE > JavaScript' 카테고리의 다른 글

2022-08-22 JS_6  (0) 2022.08.22
2022-08-18 JS_5 (배열, 반복문, 콘솔, 함수)  (0) 2022.08.19
2022-08-16 JS_4  (0) 2022.08.17
2022-08-14 JS_2  (0) 2022.08.14
2022-08-12 JS_1  (0) 2022.08.14