Post

[JS] Level 1(2)

[JavaScript 입문과 웹 UI개발] codingapple.com

[JS] Level 1(2)

function의 파라미터 문법


파라미터 문법

  • 함수와 파라미터 사용
  • (부트스트랩 불러오는 코드와 같이 src로 외부 스크립트를 불러올 때 내부 코드는 무시되기도 함. 따로 작성 필요.)
  • index.html
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
      <body>
    
          <div class="alert-box" id="alert">
              Alert
              <button class="button button-close" onclick="buttonAlert('none');"><i class="bi bi-x-lg"></i></button>
          </div>
          <button class="button button-open" onclick="buttonAlert('block');">Open</button>
    
          <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
          <script>
              function buttonAlert(x){
                  document.getElementById('alert').style.display = x;
              }
          </script>
    
      </body>
    

버튼에 따른 알림 띄우기(숙제)

자바스크립트 이벤트리스너


getElementsByClassName 셀렉터

  • Class로 찾는 셀렉터
  • getElementsByClassName('클래스명')[숫자(위에서 몇 번째 클래스인지)]

addEventListener

  • onclick과 같은 이벤트 감지 기능을 html이 아닌 스크립트 내에 작성 가능
  • 대상 + 행동 + 콜백함수(코드 실행)
  • 콜백함수: 파라미터 자리에 들어가는 함수(함수 안의 함수). 순차적으로 실행하고 싶을 때 많이 보이는 형태

서브메뉴 만들어보기와 classList 다루기


Bootstrap

  • 설치
    • css파일은 <head> 태그 안에
      1
      
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
      
    • js 파일은 <body> 태그 끝나기 전에
      1
      
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
      

클릭 시 등장하는 서브메뉴

  • (Bootstrap이 더 강한 우선순위를 가지고 있는 경우 셀렉터의 우선순위를 높여 활용)
  • 클래스 탈부착으로 기능 구현
    • 애니메이션 추가 용이
    • 재사용 편리
  • toggle 사용

querySelector()

  • CSS 셀렉터로 요소 선택 가능
    • 맨 위 요소만 찾아줌
      1
      
        document.querySelector('.list-group-item')
      
  • All은 요소 전부 찾고 인덱싱해서 지정
    1
    
      document.querySelectorAll('.list-group-item')[2]
    
This post is licensed under CC BY 4.0 by the author.