Java Script/MDN 정리

자바스크립트 구성요소 ~ 함수 만들기

Zin0_0 2020. 7. 25. 00:09
반응형

Active learning: Let's build a function

  • 본격적으로 시작하기 앞서, 기본적인 함수를 만들어봅시다..

    • function-start.html 파일을 연습하고있는 컴퓨터에 복사하여 저장합니다. HTML 구조는 매우 간단합니다. — body 태그에는 한 개의 버튼이 있습니다. 그리고 style 태그에 메시지 박스를 위한 CSS 블럭이 있습니다. 그리고 비어있는 `` 엘리먼트에 연습할 자바스크립트 코드를 앞으로 쓰겠씁니다..

    • 다음으로 아래의 코드를 script 엘리먼트에 써봅시다.

      function displayMessage() {
      
      }
    • 마지막으로 아래의 코드를 중괄호 안에 작성합니다.

      const html = document.querySelector('html');
      
      const panel = document.createElement('div');
      panel.setAttribute('class', 'msgBox');
      html.appendChild(panel);
      
      const msg = document.createElement('p');
      msg.textContent = 'This is a message box';
      panel.appendChild(msg);
      
      const closeBtn = document.createElement('button');
      closeBtn.textContent = 'x';
      panel.appendChild(closeBtn);
      
      closeBtn.onclick = function() {
          panel.parentNode.removeChild(panel);
      }
      • 첫 번째 줄에서 document.querySelector() 라는 DOM API를 사용했습니다.

        • 이 API는 엘리먼트를 선택하여 html이라는 변수에 저장합니다. 따라서 아래와 같은 작업을 수행할 수 있음
          const html = document.querySelector('html');
      • 다음 줄에선 마찬가지로 DOM API인 document.createElement() 을 사용하여

        엘리먼트를 생성한 후 panel변수에 저장. 이 엘리먼트는 메시지 상자 바깥쪽 컨테이너가 될 것 입니다.

      • 그리고 또 다른 DOM API인 Element.setAttribute() 을 사용하여 class 속성을 만들고 그 이름을 msgBox로 지정. 이 작업으로 스타일을 좀 더 쉽게 적용 가능. — HTML 파일의 CSS 블럭을 살펴보면 .msgBox 클래스 셀렉터를 사용하여 메시지 박스와 그 내용을 스타일링할 수 있음을 알 수 있다.

      • 마지막으로, Node.appendChild() DOM 함수를 사용하여 html 변수 안의 엘리먼트에 panel 변수에 저장된

        엘리먼트를 자식 엘리먼트로 삽입. 변수 선언만으로는 페이지에 표시할 수 없다. 반드시 아래처럼 작성하여 엘리먼트가 어디에 표시되는지 명시해야 한다.

        const panel = document.createElement('div');
        panel.setAttribute('class', 'msgBox');
        html.appendChild(panel);
      • 다음 두 섹션은 위에서 봤던것과 동일한 createElement() 그리고 appendChild() 함수를 사용. —

        그리고

      • 마지막으로 GlobalEventHandlers.onclick 이벤트 핸들러를 사용하여 사용자가 x버튼을 클릭하면 메시지상자를 닫을 수 있게 만든다.

        • onclick 핸들러는 버튼 (또는 실제 페이지의 다른 엘리먼트) 에서 사용 가능
        • 버튼이 클릭됐을때 실행될 코드를 작성할 수 있다. 더 자세한 기능은 events article을 참조.
        • 이제 onclick 핸들러를 익명 함수와 동일하게 만들고, 그 안에 버튼이 클릭됐을 때 실행될 코드를 작성.
        • 함수 안쪽에서 Node.removeChild() DOM API 함수를 사용하여 HTML 엘리먼트를 삭제하도록 명령. — 이 경우 panel 변수의

          closeBtn.onclick = function() {
          panel.parentNode.removeChild(panel);
          }
      • 기본적으로 전체 코드 블럭은 아래처럼 보이는 HTML 블록을 생성하고 페이지에 나타내줍니다.

        <div class="msgBox">
          <p>This is a message box</p>
          <button>x</button>
        </div>

함수 불러오기

  • script안에서 불러오면 정상 작동되는 것을 확인할 수 있음
    displayMessage();
  • Display message box 버튼을 누를 때마다 뜨도록 스크립트 설정
    const btn = document.querySelector('button');
    btn.onclick = displayMessage;
  • 괄호를 포함해서 작성해보자
    const btn = document.querySelector('button');
    btn.onclick = displayMessage();
    • 이 경우, 처음 페이지 로딩시에 창이 한번 뜨고, click을 해도 반응이 없다.
    • 이 맥락에서 괄호는 때때로 "기능 호출 연산자"라고 불린다. 현재 범위에서 즉시 기능을 실행하려는 경우에만 이 기능을 사용해야 한다. 익명함수 내부의 코드는 함수 범위 내에 있기 때문에 즉시 실행되지 않는다

파라메터로 함수 기능 향상하기

  • 위의 경우, 계속 하나의 문구만 생성되므로 생산성이 없다. 아래와 같이 파라메터를 추가해서 생상성을 높여보자
    function displayMessage(msgText, msgType) {
        ...
        msg.textContent = msgText;
    }
    ...
    displayBtn.onclick = () => {
        displayMessage("Woo, this is a different message!");
    };

A more complex parameter

msgType에 따라서 css를 바꿔보자.

  • 페이지의 링크는 사라졌으니, 구글에서 warning과 chat 이미지 다운받아서 icons/디렉토리 안에 넣기

  • css 변경하기

    width: 242px;
    
    .msgBox p {
        ...
        padding-left: 82px;
        background-position: 25px center;
        background-repeat: no-repeat;
    }
  • script 추가하기

    ...
    
    if (msgType === 'warning') {
        msg.style.backgroundImage = 'url(icons/warning.png)';
        panel.style.backgroundColor = 'red';
    } else if (msgType === 'chat') {
        msg.style.backgroundImage = 'url(icons/chat.png)';
        panel.style.backgroundColor = 'aqua';
    } else {
        msg.style.paddingLeft = '20px';
    }
    
    const closeBtn = document.createElement('button');
    ...
    const displayBtn = document.querySelector('button');
        displayBtn.onclick = () => {
            displayMessage('Your inbox is almost full — delete some mails', 'warning');
            displayMessage('Brian: Hi there, how are you today?','chat');
    };
반응형