https://cdnjs.com/libraries/jquery
jquery - Libraries - cdnjs - The #1 free and open source CDN built to make life easier for developers
JavaScript library for DOM operations - Simple. Fast. Reliable. Content delivery at its finest. cdnjs is a free and open-source CDN service trusted by over 12.5% of all websites, serving over 200 billion requests each month, powered by Cloudflare. We make
cdnjs.com
위 링크에 들어가서 사진과 같은 링크를 복사해줍니다.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
script의 src 속성에 복사한 내용을 적어줄 것입니다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/jquery/hello.jsp</title>
<!-- jquery 로딩 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
</body>
</html>
위와 같이 html에 추가해줍니다.
이제 jquery를 사용하기 위한 준비는 끝났습니다. 본격적으로 사용해봅시다!
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/jquery/hello.jsp</title>
<!-- jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<p>p1</p>
<p class="my-class">p2</p>
<p class="my-class">p3</p>
<p class="my-class">p4</p>
<p class="my-class">p5</p>
<button id="changeBtn">바꾸기</button>
<button id="changeBtn2">바꾸기2</button>
<script>
//바꾸기 버튼을 눌렀을때 모든 p요소의 글자색을 빨간색으로 바꿔보세요.
document.querySelector("#changeBtn").addEventListener("click",function(){
//모든 p 요소의 참조값을 배열에 담아오기
let ps=document.querySelectorAll("p");
//반복문 돌면서
for(let i=0;i<ps.length;i++){
//각각의 p요소 글자색을 red로 바꾸기
ps[i].style.color="red";
}
});
$("#changeBtn2").on("click",function(){
$("p").css("color","red");
});
</script>
</body>
</html>
위 예제는 바꾸기 버튼을 눌렀을때 모든 p요소의 글자색을 모두 빨간색으로 바꾸는 예제입니다.
html과 jquery에서 변경법을 각각 봅시다.
html에서는 querySelecter을 사용하여 객체의 참조값을 구해서 바꿉니다.
jquery에서는 $와 .on을 사용하여 바꿉니다.
$("button")을 보면 query기능이 합쳐진 버튼 객체 배열을 리턴하는 모습을 볼 수 있습니다.
$("p")을 보면 query기능이 합쳐진 p 객체 배열을 리턴하는 모습을 볼 수 있습니다.
$는 document.querySelectorAll("p")와 비슷하지만 $가 리턴한 배열의 기능이 훨씬 많습니다.
클래스명은 .으로 id는 #으로 접근해주시면됩니다. 액션 부분은 on()말고도 .css(), .val(), .text()와 같이 많은 기능들이 있습니다.
jquery의 특별한 기능 중 하나는 chainAction입니다. .을 사용하여 계속해서 사용하여 속성을 지정할 수 있는 기능입니다.
하지만 항상 할 수 있는 것은 아닙니다.
위 예제를 보면 div1이라는 string 이 반환된것을 볼 수 있습니다. 이때 . 을 사용하면 오류가 나는 모습을 볼 수 있습니다.
즉, query기능이 합쳐진 배열을 리턴하지 않으면 chainAction을 사용할 수 없습니다.
'WEB' 카테고리의 다른 글
[JSP/Servlet] Filter 사용하기 / 인코딩 필터, 로그인 필터 (0) | 2021.11.29 |
---|---|
[WEB] Forward & Redirect 개념과 차이점, 예제 (0) | 2021.11.29 |
[Eclipse] 프로젝트 import 할 때 나타나는 버전 오류 해결법 (0) | 2021.11.29 |
[JSP/Servlet] session 구현해보기 / 로그인 유지하는 방법 (0) | 2021.11.29 |
[WEB] JSP를 사용하여 동적 웹 사이트 만들어보기/ JSP와 Servlet 비교 (1) | 2021.11.26 |