[JavaScript기초] 7. jQuery 사용법
- jQuery 설치
구글에 jQuery cdn 검색 https://releases.jquery.com/
jQuery CDN
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libr
releases.jquery.com
jQuery 3.x 버전 <script> 태그를 찾아서 html 파일에 복사 붙여 넣기
<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>
아니면, 최신버전 jQuery 사용하려면 아래 코드를 body안에 넣어준다.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
- jQuery 사용 (1 ~ 5까지 예시)
1. html 변경
이전 포스팅에서 자바스크립트로 html을 변경하는 방법을 보았다.
<p class="hello">안녕</p>
<script>
document.querySelector('.hello').innerHTML = 'hello'
</script>
해당 코드를 jQuery를 사용하게된다면
$('.hello').html('hello');
위와 같이 간단하게 작성이 가능하다.
2. 스타일 변경
<p class="hello">안녕</p>
<script>
$('.hello').css('color', 'red');
</script>
참고로, html 셀렉터( querySelector)로 찾으면 html 함수들(ie. innerHTML)을 사용해야하고,
jQuery 셀렉터로 찾으면 jQuery 함수들(ie. html)을 사용해줘야한다.
$('.hello).innerHTML = 'hello';
위 코드는 잘못된 예시이다.
3. class 탈부착 방법 (아래 링크와 비교해보면 jQuery 함수와 html 함수와 차이점을 알 수 있다.)
<p class="hello">안녕</p>
<script>
$('.hello').addClass('클래스명');
$('.hello').removeClass('클래스명');
$('.hello').toggleClass('클래스명');
</script>
https://midnightcoding.tistory.com/101
[JavaScript기초] 6. classList 다루기 (서브메뉴 숨기기)
이전 포스팅에서 bootstrap을 이용하여, Navbar구현하는 법에 대해서 알아보았다. https://midnightcoding.tistory.com/100 [JavaScript기초] 5. 부트스트랩 사용하는법(bootstrap) 부트스트랩은, 기존에 만들어 놓은 Na
midnightcoding.tistory.com
또한, jQuery를 사용하게 되면, 한번에 같은 class를 모두 변경 할 수있는 장점이있다.
<p class="hello">안녕</p>
<p class="hello">안녕</p>
<p class="hello">안녕</p>
<script>
$('.hello').html('바보');
</script>
위에 class='hello' 인 3가지 <p> tag의 html 을 한번에 다 바꿔 줄 수있다.
4. 이벤트 리스너 사용방법
<p class="hello">안녕</p>
<button class="test-btn">버튼</button>
<script>
$('.test-btn').on('click', function(){
어쩌구~
});
</script>
html에서 사용하였던, addEventListener 대신 on 을 쓰면된다.
앞에서 이야기한대로, on 같은 함수는 jQuery 문법 즉, $() 이걸로 찾은 것들에만 붙일 수 있다.
5. UI 애니메이션 사용법
<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() 이런 것도 있음
출처 : 코딩애플 'JavaScript 입문과 웹 UI개발'