HTML CSS JS

jQuery 사용법

개발자 누렁이 2025. 1. 21. 23:50
728x90
반응형

jQuery cdn 검색해서 <script> 복사 후 붙여넣기

 

<body>태그 끝나기 전에 넣는거 권장함, 위에서부터 코드를 읽기 때문에 성능면에서 유리함

 

자바스크립트 querySelectorAll, addEvenListener, classList.add 같은 것들을 이름만 훨씬 짧게 바꿔주는 라이브러리임

 

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> 


위 코드를 <script> 태그를 찾아 html파일에 복붙하면 설치 끝

 

<p class="hello">안녕</p>

<script>
  $('.hello').html('바보'); 
</script>

 

$는 querySelector와 동일하게 사용됨

 

<script>
  $('.hello').css('color', 'red');
</script>

 

이렇게 css 스타일 변경이 가능함

 

<p class="hello">안녕</p>

<script>
  $('.hello').addClass('클래스명');
  $('.hello').removeClass('클래스명');
  $('.hello').toggleClass('클래스명');
</script>

 

jQuery 써서 class 탈부착가능

 

<p class="hello">안녕</p>
<p class="hello">안녕</p>
<p class="hello">안녕</p>

<script>
  document.querySelectorAll('.hello')[0].innerHTML = '바보';
  document.querySelectorAll('.hello')[1].innerHTML = '바보';
  document.querySelectorAll('.hello')[2].innerHTML = '바보';
</script>
<p class="hello">안녕</p>
<p class="hello">안녕</p>
<p class="hello">안녕</p>

<script>
  $('.hello').html('바보');
</script>

$()셀렉터는 그냥 querySelectorAll처럼 여러개가 있으면 전부 찾아준다.

 

<p class="hello">안녕</p>
<button class="test-btn">버튼</button>

<script>
  $('.test-btn').on('click', function(){
    어쩌구~
  });
</script>

 

이벤트 리스너는 on을 쓰면 똑같다.

on은 $() 로 찾은 것들에만 붙일 수 있다.

 

<p class="hello">안녕</p>
<button class="test-btn">버튼</button>

<script>
  $('.test-btn').on('click', function(){
    $('.hello').fadeOut();
  });
</script>

 

.hide() 사라지게

.fadeOut()는 서서히 사라지게

.slideUp()은 줄어들며 사라지게

show(), fadeIn(), slideDown(),fadeToggle() 등이 있다.

 

느낀점

 

'안녕'이 '바보'로 바뀌지 않았는데 처음에 <script>태그를 제대로 닫지 않아 </script>가 빠져 있는 부분이 코드에 포함되어 있어, 이후의 스크립트가 제대로 실행되지 않았다.

 

 

<script
  src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
  integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
  crossorigin="anonymous"
></script>
<script>
  $('.hello').html('바보');
</script>

이렇게 해결하였고,

 

$('#test-btn').on('click', function () {
  console.log('Button clicked!');
});

 

이부분을 작성할때 function을 fuction 으로 오타를 내서 코드가 작동하지 않았다.

 

  <body>
    <button id="test-btn">Click me</button>
    <p class="hello">Hello</p>

    <script>
      // Native JavaScript
      document.querySelector("#test-btn").addEventListener("click", function () {
        console.log("Native JS Button clicked!");
      });

      // jQuery
      $("#test-btn").on("click", function () {
        $(".hello").slideUp();
      });
    </script>
  </body>

 

Native JavaScript 문이랑 JQuery문을 같이 작성해서 실행되지 않았던 부분도 있었다.

728x90
반응형

'HTML CSS JS' 카테고리의 다른 글

369게임과 응용방법  (1) 2025.01.31
input, change 이벤트와 and, or 연산자  (0) 2025.01.30
모달창만들기와 애니메이션 만들기  (0) 2025.01.24