jQuery
1. 개요
- JS 의 라이브러리
- 풍부한 기능이 제공
- 사용하기도 쉽다.
- *.js 형식으로 제공됨.
- https://jquery.com/
2. 설치방법 2가지
1> 다운로드
- *.js 파일을 local 에 저장해서 사용.
- 2가지 버전
압축버전: *.js (배포용, 용량을 공백을 제거해서 거의 한줄로 되어있음.)
-> jquery-3.7.1.min.js(86KB)
비압축버전: *.js (개발용)
-> jquery-3.7.1.js(279KB)
2> CND(Content Delivery Network)
- 서버와 링크 이용해서 사용.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
==> 만약에 jquery 의 js를 인식을 못하면
jQuery01_설치1_다운로드방식.html:11 Uncaught ReferenceError:
$ is not defined 에러가 발생된다.
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery01_설치1_다운로드방식</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 다운로드 방식(개발방식) -->
<script src="jquery-3.7.1.js"></script>
<script>
// jQuery 코드 및 js 코드 작업
console.log("JS 객체: ", document);
console.log("jQuery 객체: ", $(document));
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery01_설치2_CDN</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CDN: 링크방식 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
// jQuery 코드 및 js 코드 작업
console.log("JS 객체: ", document);
console.log("jQuery 객체: ", $(document));
</script>
</head>
<body>
</body>
</html>
3. JS 객체 vs jQuery 객체
- 문법: jQuery(JS객체)
jQuery 의 별칭이 $ 임.
일반적으로 $ 를 주로 사용한다.
- $(JS객체) 사용하면 JS 객체가 jQuery 객체로 변환되어 반환됨.
ex>
JS 객체: document, this, ...
==> JS용 객체에서 제공하는 속성/메서드를 사용해야 된다.
ex> document.querySelector()
jQuery 객체: $(document), $(this), ...
==> jQuery용 객체에서 제공하는 속성/메서드를 사용해야 된다.
ex> $(document).css()
4. ready() 메서드
https://api.jquery.com/ready/#ready-handler
- 문법:
$(document).ready(function(){});
$("documet").ready(function(){});
- JS 의 window.onload=init; 과 동일한 기능.
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery02_ready메서드</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- reday 메서드 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
// document.querySelector("p").innerText = "world";
// 에러가 나는데 js 에서는 아래의 방식을 사용했다.
// function init() {
// document.querySelector("p").innerText = "world";
// }
// ready 사용 ----------------------------------------------
// window.onload 와 동일한 기능
// $(document).ready(function () { //jQuery 객체
// // document.querySelector("p").innerHTML = "world"; // JS 객체
// console.log($("p"));
// $("p").text("world2"); // jQuery 객체
// });
//-----------------------------------
$(document).ready(function () { //jQuery 객체
console.log("DOM Tree 가 완료된 후 함수호출");
});
</script>
</head>
<body>
<p>Hello</p>
</body>
<!-- <body onload="init()">
<p>Hello</p>
</body> -->
</html>
5. DOM 선택하는 방법
문법:
$(선택자) <== 기존의 document.querySelector(선택자) 문법과 동일한 기능
ex>
$("p")
$("#xxx")
$(".yyy")
$("a[href]")
$("div > p")
ex>
<p id="xxx">hello</p>
var p = $("#xxx"); // jQuery
var p2 = document.querySelector("#xxx"); // JS
<!DOCTYPE html>
<html lang="en">
<head>
<title>js12_DOM처리12_this</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
function fun() {
var input_data = document.querySelector("#xxx").value;
console.log("fun: ", input_data);
}
function fun2() {
console.log(this); // this ==> window 객체
}
function fun3(x) {
console.dir(x); // HTMLInputElement
console.log(x); // 전달된 this? HTMLInputElement
// x 와 document.querySelector("#xxx3") 와 동일한 값이다.
console.log(x.value); // xxx3
}
</script>
</head>
<body>
id: <input type="text" id="xxx" onkeyup="fun()"><br>
id2: <input type="text" id="xxx2" onkeyup="fun2()"><br>
id3: <input type="text" id="xxx3" onkeyup="fun3(this)"><br>
</body>
</html>
6. Selectors
1> basic + attribute + hierarchy
https://api.jquery.com/category/selectors/basic-css-selectors/
https://api.jquery.com/category/selectors/attribute-selectors/
https://api.jquery.com/category/selectors/hierarchy-selectors/
<script>
$(document).ready(function(){
//1. 모든 태그 선택
// console.log(jQuery("*"));
//$("*").css("color","red");
//2. 특정 태그 선택
// $("p").css("color","red");
//3. id로 선택
//$("#x").css("color","red");
//4. class로 선택
// $(".y").css("color","red");
//5. 여러개 선택
// $("#x, .z").css("color","red");
//6. 속성으로 선택
// https://api.jquery.com/category/selectors/attribute-selectors/
// $("[class]").css("color","red");
// $("[class='z']").css("color","red");
// $("a[href^='https']").css("color","red");
// $("a[href$='com']").css("color","red");
// 7. 계층구조 - 자식/자손
// https://api.jquery.com/category/selectors/hierarchy-selectors/
// 자식 선택
// $("div > a").css("color","red");
// 자손 선택 ( 자식포함 )
// $("div a").css("color","red");
// 8. 계층구조 - 형제/형제들
// 바로 뒤 형제
// $("p+a").css("color","red");
// 뒤 형제들
$("p~a").css("color","red");
});
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery03_selectors1_basic_attribute_hierarchy</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- reday 메서드 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () { //jQuery 객체
// 1. 모든 태그 선택
// console.log(jQuery("*"));
// console.log($("*"));
// $("*").css("color", "red");
// 2. 특정 태그 선택
// $("p").css("color", "red");
// 3. id 로 선택
// $("#x").css("color", "red");
// 4. class 로 선택
// $(".y").css("color", "red");
// 5. 여러개 선택
// $("#x, .z").css("color", "red");
// 6. 속성으로 선택
// https://api.jquery.com/category/selectors/attribute-selectors/
// $("[class]").css("color", "red");
// 6-1. 속성 + 값
// $("[class='z']").css("color", "red");
// 6-2. https 로 시작
// $("a[href^='https']").css("color", "red");
// 6-3. com 으로 끝
// $("a[href$='com']").css("color", "red");
// 7. 계층구조 - 자식/자손
// https://api.jquery.com/category/selectors/hierarchy-selectors/
// 자식 선택
// $("div > a").css("color", "red");
// 자손 선택(자식포함)
// $("div a").css("color", "red");
// 8. 계층구조 - 형제/형제들
// 바로 뒤 형제
// $("p+a").css("color", "red");
// 뒤 형제들
$("p~a").css("color", "red");
});
</script>
</head>
<body>
<div>
<p class="y">셀렉터</p>
<a href="http://naver.com" class="y">naver</a><br>
<a href="http://daum.net" class="y">daum</a><br>
<a href="https://google.com" class="z">google</a><br>
<p>
<a href="#" id="x">자손</a>
</p>
<p>
<span><a href="xxx">자손2</a></span>
</p>
</div>
</body>
</html>
2> Filter- Basic, Child, Content
<script>
$(document).ready(function () { //jQuery 객체
// https://api.jquery.com/category/selectors/child-filter-selectors/
// 1. first-child: li 부모태그 기준의 첫번째 자식인 li 반환
// $("li:first-child").css("color", "red");
// 2. :last-child: li 부모태그 기준의 마지막 자식인 li 반환
// $("li:last-child").css("color", "red");
// 3. :nth-child(n): li 부모태그 기준의 n번째 자식인 li 반환
// $("li:nth-child(2)").css("color", "red");
// 4. :nth-child(2n): li 부모태그 기준의 2n번째(2배수, 짝수)
// 자식인 li 반환, 1부터
// $("li:nth-child(2n)").css("color", "red");
// 5. :nth-child(2n+1): li 부모태그 기준의 2n+1번째(2배수+1, 홀수)
// 자식인 li 반환, 1부터
// $("li:nth-child(2n+1)").css("color", "red");
// 6. :only-child: li 부모태그 기준의 유일한 자식인 li 반환
// $("li:only-child").css("color", "red");
});
</script>
* 추가정리
span:last-child Selector
==> span의 부모기준으로 마지막이 span 으로 되어 있어야 반환됨.
span:last-of-type Selector
==> span 의 부모기준으로 DOM 에서 가장 마지막인 span 을 반환함.
가장 마지막이 span이 아니어도 무관함.
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery03_selectors2_Filter1_child</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- reday 메서드 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
// https://api.jquery.com/category/selectors/child-filter-selectors/
// 1. first-child: li 부모태그 기준의 첫번째 자식인 li 반환
// $("li:first-child").css("color", "red");
// 2. :last-child: li 부모태그 기준의 마지막 자식인 li 반환
// $("li:last-child").css("color", "red");
// 3. :nth-child(n): li 부모태그 기준의 n번째 자식인 li 반환
// $("li:nth-child(2)").css("color", "red");
// 4. :nth-child(2n): li 부모태그 기준의 2n번째(2배수, 짝수)
// 자식인 li 반환, 1부터
// $("li:nth-child(2n)").css("color", "red");
// 5. :nth-child(2n+1): li 부모태그 기준의 2n+1번째(2배수+1, 홀수)
// 자식인 li 반환, 1부터
// $("li:nth-child(2n+1)").css("color", "red");
// 6. :only-child: li 부모태그 기준의 유일한 자식인 li 반환
// $("li:only-child").css("color", "red");
});
</script>
</head>
<body>
<ul>
<li>AAAA</li>
</ul>
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
<li>e</li>
<li>f</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery03_selectors2_Filter1_child2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- reday 메서드 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
// https://api.jquery.com/category/selectors/child-filter-selectors/
// 1. :last-child: span 부모태그 기준의 마지막 자식인 span 반환
$("span:last-child").css("color", "red");
// 2. :last-of-type: span 부모태그 기준의 마지막 자식인 span 반환
// 진짜 마지막 자식이 span 과 무관.
$("span:last-of-type").css("font-size", "40px");
});
</script>
</head>
<body>
<div>
<span>AAA1</span>
<span>AAA2</span>
<span>AAA3</span>
<span>AAA4</span>
</div>
<div>
<span>BBB1</span>
<span>BBB2</span>
<span>BBB3</span>
<span>BBB4</span>
<p>CCC</p>
</div>
</body>
</html>
다. Content
https://api.jquery.com/category/selectors/content-filter-selector/
<script>
$(document).ready(function () {
// https://api.jquery.com/category/selectors/content-filter-selector/
// 1. :contains(문자열) ==> 문자열을 포함하는 요소 반환
// 대소문자 구분하고 포함만 하면 반환해줌
// $("div:contains('John')").css("color", "red");
// 2. :has(선택자) ==> 선택자를 포함하는 요소 반환
// $("div:has('p')").css("color", "red");
// 3. :empty ==> 자식이 없는 요소 반환
// $("td:empty").css("background-color", "red");
// 4. :parent ==> empty 반대로 자식이 있 요소 반환
// $("td:parent").css("background-color", "red");
});
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery03_selectors2_Filter2_content</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- reday 메서드 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
// https://api.jquery.com/category/selectors/content-filter-selector/
// 1. :contains(문자열) ==> 문자열을 포함하는 요소 반환
// 대소문자 구분하고 포함만 하면 반환해줌
// $("div:contains('John')").css("color", "red");
// 2. :has(선택자) ==> 선택자를 포함하는 요소 반환
// $("div:has('p')").css("color", "red");
// 3. :empty ==> 자식이 없는 요소 반환
// $("td:empty").css("background-color", "red");
// 4. :parent ==> empty 반대로 자식이 있 요소 반환
// $("td:parent").css("background-color", "red");
});
</script>
</head>
<body>
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom john Sinclair</div>
<div>
<p>HiJohn Resig</p>
</div>
<table border="1">
<tr>
<td>TD #0</td>
<td></td>
</tr>
<tr>
<td>TD #2</td>
<td></td>
</tr>
<tr>
<td></td>
<td>TD #5</td>
</tr>
</table>
</body>
</html>
라. Form
https://api.jquery.com/category/selectors/form-selectors/
<script>
$(document).ready(function () {
// https://api.jquery.com/category/selectors/form-selectors/
// 1. 버튼 요소 반환
var button = $(":button");
var b1 = button[0];
console.log(button); // jQuery 객체
console.log(b1); // JS 객체
console.log(b1.innerText); // JS 객체
// JS -> jQuery
var b1_jquery = $(b1); // jQuery 객체로 바뀜.
// text(값) -> 값은 setter 역할 , text() 는 getter 역할
// text() 는 JS 의 innerText 역할
console.log(b1_jquery.text());
// 체크박스에서 체크된 요소 반환
// val() 는 JS 의 value 역할
// val(값) -> 값은 setter 역할, val() 은 getter 역할
var checkbox_checked = $("input:checked");
console.log(checkbox_checked); // jQuery 객체 반환
console.log(checkbox_checked.val()); // JS 객체 반환
// - JS 이용
var js = document.querySelector("#kkk").value;
console.log("js: ", js);
});
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery03_selectors2_Filter3_form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- reday 메서드 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
// https://api.jquery.com/category/selectors/form-selectors/
// 1. 버튼 요소 반환
var button = $(":button");
var b1 = button[0];
console.log(button); // jQuery 객체
console.log(b1); // JS 객체
console.log(b1.innerText); // JS 객체
// JS -> jQuery
var b1_jquery = $(b1); // jQuery 객체로 바뀜.
// text(값) -> 값은 setter 역할 , text() 는 getter 역할
// text() 는 JS 의 innerText 역할
console.log(b1_jquery.text());
// 체크박스에서 체크된 요소 반환
// val() 는 JS 의 value 역할
// val(값) -> 값은 setter 역할, val() 은 getter 역할
var checkbox_checked = $("input:checked");
console.log(checkbox_checked); // jQuery 객체 반환
console.log(checkbox_checked.val()); // JS 객체 반환
// - JS 이용
var js = document.querySelector("#kkk").value;
console.log("js: ", js);
});
</script>
</head>
<body>
<button>버튼1</button>
<form>
<button>버튼2</button>
<input type="text" name="aaa">
<input type="text" name="bbb" disabled="disabled">
<input type="checkbox" name="bbb" value="xxx">
<input type="checkbox" name="ccc" value="xxx2" id="kkk" checked>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</body>
</html>
####################################################################
7. Traversing
https://api.jquery.com/category/traversing/filtering/
- 위의 `6. Selectors` 는 DOM 에서 1차로 필터링하는 방법이다.
7. Traversing 는 기본 Selectors 로 1차 필터링하고 이후에 2차 필터링할 때 사용한다.
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery04_2차필터링1_Filtering</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- reday 메서드 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
// https://api.jquery.com/category/traversing/filtering/
// 1. .eq(idx) <== 0 부터 시작. 지정된 idx 값을 2차 필터링
// $("li").eq(0) -> $("li"): 1차 필터링 , .eq(0): 2차 필터링
// $("li").eq(0).css("color", "red");
// 2. .filter(selector) <== 지정된 selectors 값으로 2차 핕터링
// $("p").filter(".middle").css("color", "red");
// 3. .not(selector) <== 지정된 selectors 값으로 일치하지 않는 2차 핕터링
// p 를 1차 필터링으로 뽑고 .middle 이 아닌 것만 필터링
// $("p").not(".middle").css("color", "red");
// 4. .first() <== 1차 필터링에서 첫번째 요소 2차 핕터링
// $("li").first().css("color", "red");
// 5. .last() <== 1차 필터링에서 마지막 요소 2차 핕터링
// $("li").last().css("font-size", "50px");
// 6. .has(selector) <== 지정된 selector 를 가진 요소를 포함하는 2차 핕터링
// $("li").has("span").css("color", "red");
// 7. .is(selector|function) <== 지정된 selector 를 가진 요소가 있으면 true
// 없으면 false 반환
// var result = $("p").is("[class]");
// console.log(result); // true
// var result = $("p").is("[id]");
// console.log(result); // false
// 8. .slice(start[, end]) <== 지정된 start 와 end 범위를 가진 2차 필터링
// start 는 0부터 시작, end 를 지정하지 않을시 끝까지 필터링
// $("li").slice(3).css("color", "red"); // 3 ~ 끝까지
// $("li").slice(2, 5).css("font-size", "50px"); // 2 ~ 4 까지
// 9. .map(function(idx,v){}) <== 1차 필터링된 요소를 가공해서 다시 반환하는 역할
// 가. JS 객체로 대문자로 변경해서 반환하는 코드
var result = $("li").map(function (idx, v) {
console.log(idx, v);
console.log(v); // JS 객체
var str = v.innerHTML;
return str.toUpperCase();
});
console.log(result);
console.log("--");
// 나. jQuery 객체로 대문자로 변경해서 반환하는 코드
var result2 = $("li").map(function (idx, v) {
console.log(v); // v 는 js 객체
var v_jquery = $(v); // v_jquery 는 jQuery 객체
var str = v_jquery.text();
return str.toUpperCase();
});
console.log(result2);
console.log("--");
// 다. function 함수내에서 JS 용 this 사용
var result3 = $("li").map(function (idx, v) {
// this 와 v 는 동일
console.log("this: ", this); // js 객체
return this.innerHTML.toUpperCase();
});
console.log(result3);
console.log("--");
// 라. function 함수내에서 jQuery 용 this 사용
var result4 = $("li").map(function (idx, v) {
// this 와 v 는 동일. 즉 li 임
console.log("this: ", this); // js 객체
var this_jQyery = $(this); // jQuery 용
return this_jQyery.text().toUpperCase();
});
console.log(result4);
});
</script>
</head>
<body>
<p>text</p>
<p class="middle">Middle <span>text</span></p>
<p class="final">final text</p>
<div>
<ul>
<li>list item1</li>
<li>list item2</li>
<li><span>list item3</span></li>
<li>list item4</li>
<li>list item5</li>
<li>list item6</li>
<li>list item7</li>
<li>list item8</li>
</ul>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery04_2차필터링2_Tree</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- reday 메서드 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
// https://api.jquery.com/category/traversing/tree-traversal/
// 1. .children([selector])
// - .children() <== 1차 핕터링의 모든 자식 반환(자손포함x)
// - .children(selector) <== 1차 핕터링의 자식들중에서
// selector와 일치하는 자식 반환(자손포함x)
// $("div").children().css("color", "red");
// $("div").children("span").css("color", "red");
// 2. .find(selector) : 자손까지 찾음(자식포함)
// $("div").find("span").css("color", "red");
});
</script>
</head>
<body>
<div>
<span>this is 1st p</span>
</div>
<div>
<p>
<span>this is 2nd p</span>
</p>
</div>
<div class="myClass">
<span>this is 3rd p</span>
</div>
<div>
<p>this is 4rd p</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery04_2차필터링2_Tree2_find와filter차이점</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- reday 메서드 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
// 2차 필터링에서 사용되는 find 와 filter 의 차이점
// filter: 1차 필터링된 div 태그중에서 class = "myClass" 로 된 요소 반환
$("div").filter(".myClass").css("color", "red");
// find: 1차 필터링된 div 태그의 자손중에서 class = "myClass" 로 된 요소 반환
$("div").find(".myClass").css("font-size", "50px");
});
</script>
</head>
<body>
<div>
<span class="myClass">this is 1st p</span>
</div>
<div>
<p>
<span>this is 2nd p</span>
</p>
</div>
<div class="myClass">
<span>this is 3rd p</span>
</div>
<div>
<p>this is 4rd p</p>
</div>
</body>
</html>
'[study]이론정리 > HTML & CSS & JavaScript' 카테고리의 다른 글
jQuery 2일차(2) - 이벤트, Ajax (0) | 2024.05.20 |
---|---|
jQuery 2일차 - Traversing(필터링), Attributes, Manipulation, Util (0) | 2024.05.20 |
js 이론정리 (0) | 2024.05.16 |
js 6일차 - 비동기, Ajax (0) | 2024.05.16 |
js 6일차 - 클래스, 모듈 (0) | 2024.05.16 |