
jQuery란 적게 작성하고 더 많이 수행하는 JavaScript 라이브러리이다.
jQuery의 목적은 웹 사이트에서 JavaScript를 훨씬 쉽게 사용할 수 있도록 하는 것이다.
jQuery는 수행하는데 많은 JavaScript 코드가 필요한 많은 일반적인 작업을 수행하고 한 줄의 코드로 호출할 수 있는 메서드로 wrapping한다. jQuery는 또한 AJAX 호출 및 DOM 조작과 같은 JavaScript의 많은 복잡한 작업을 단순화한다.
jQuery 라이브러리에는 다음 기능이 포함된다
많은 JavaScript 라이브러리가 있지만 jQuery가 가장 인기있고 확장 가능하다.
웹 사이트에서 jQuery 사용하는 두 가지 방법
<head>
<script src="jquery-3.6.1.min.js"></script>
</head>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
jQuery 구문은 HTML element를 선택하고 element에 대해 일부 작업을 수행하기 위해 맞춤 제작되었다.
기본 syntax:
$(selector).action()
jQuery는 elements를 선택하기 위해 CSS syntax를 사용한다.
$("p").hide() // 모든 <p> 태그 숨기기
$(".test").hide() // 클래스가 "test"인 모든 요소 숨기기
$("#test").hide() // id가 "test"인 모든 요소 숨기기
jQuery methods는 document ready event안에 있어야 한다.
$(document).ready(function() {
// jQuery methods go here...
});
이유:
document load가 끝나기도 전에 jQuery code가 실행되는것을 막기 위함이다. 이것은 또한 document body 전, head section에 JavaScript 코드를 가질 수 있게 한다.
document ready event 더 짧은 버전
$(function() {
// jQuery methods go here...
});
jQuery에 있는 모든 selector들은 $() 이렇게 시작한다.
<head>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
<script>
<head>
<head>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
<script>
<head>
<head>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
<script>
<head>
이외에도
$("*") // 전체 elements
$(this) // 현재 html element
$("p.intro") // 클래스가 "intro"인 모든 p태그
$("ul li:first") // 첫 번째 <ul> 태그의 첫 번째 <li>태그
이렇게 <head> 에다가 jQuery functions를 넣을 수 있지만 코드가 너무 길고 복잡해진다면 .js 파일을 따로 만들어서 관리하는게 좋다.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script>
</head>
jQuery는 HTML 페이지의 이벤트에 응답하도록 맞춤 제작되었다.

대부분의 DOM event에는 동일한 jQuery 함수들이 있다.
예를 들어 페이지 내에 있는 모든 p태그에 클릭 이벤트 할당하고 클릭 이벤트가 일어났을 때 어떤 이벤트가 발생할지 정의하려면
$("p").click(function(){
// action goes here!!
});
이런식으로 코드를 작성하면 된다.
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});: 선택된 elements에 대해 하나이상의 이벤트 헨들러를 부여
$("p").on("click", function(){
$(this).hide();
});
p 태그에 여러 이벤트 헨들러 부여하기
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css("background-color", "yellow");
}
});
$(selector).hide(speed, callback); // html element 숨기기
$(selector).show(speed, callback); // html element 보여주기
speed 파라미터에는 "slow", "fast" or milliseconds 중 하나의 값을 가질 수 있다.
: 해당 element가 숨겨진 상태라면 보여주고 보여진 상태라면 숨기기
$("button").click(function(){
$("p").toggle();
});
자바스크립트 코드는 한줄씩 한줄씩 실행되는데 어떤 효과가 아직 끝나지도 않았는데 그 다음 줄 코드가 실행되는 에러가 발생할 수 있다. 이걸 막기 위해 callback 함수를 만든다. callback함수는 현재 effect가 100% 끝난 뒤에 실행된다.
$(selector).hide(speed, callback);
hide 효과가 완전히 끝난 뒤에 alert 창을 띄우라는 callback 함수가 실행된다.
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
지금까지 우리는 한 번에 하나씩 jQuery 문을 작성해 왔다. 그러나 동일한 element에서 여러 jQuery 명령을 차례로 실행할 수 있는 chain 이라는 기술이 있다. 이렇게 하면 브라우저가 동일한 요소를 두 번 이상 찾을 필요가 없다는 장점이 있다.
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
"p1" element는 먼저 빨간색으로 변경된 다름 위로 슬라이드한 다음 아래로 슬라이드 한다.
jQuery는 HTML elements와 attributes를 변경하고 조작할 함수를 가지고 있다.
DOM 조작을 위한 세 가지 유용한 jQuery method
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
$("#btn1").click(function(){
alert("Value: " + $("#test").val());
});
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
$("p").append("Some appended text.");
jQuery remove() 함수는 제거할 요소를 필터링하기 위해 하나의 파라미터를 받을 수 있다.
$("p").remove(".test, .demo");
jQuery를 사용하면 elements의 스타일을 쉽게 조작할 수 있다.
여러 개의 클래스 지정 가능
$("button").click(function(){
$("#div1").addClass("important blue");
});
$("p").css("background-color");
첫번째로 매치된 element의 배경색 값 반환한다.
$("p").css("background-color", "yellow");
매치된 모든 elements에 노란색 배경색을 설정한다.
$("p").css({"background-color": "yellow", "font-size": "200%"});