💁♀️ 제이쿼리(jQuery)란,
기존 복잡했던 클라이언트 측 HTML 스크립팅을 간소화 하기 위해 고안된 JavaScript 라이브러리로, 적은 양의 코드로 빠르고 풍부한 기능을 제공
jQuery 공식 사이트
jQuery 라이브러리 제공 페이지
- [Way 1] jQuery 라이브러리 다운로드를 통한 연결
: js 파일을 다운로드 하여 파일 경로 지정- [Way 2] CDN(Content Delivery Network)을 통한 연결
: 제공하는 주소를 이용하여 파일 경로 지정
💁♀️ 아래의 소스를 jQuery가 사용된 파일마다의 head에 삽입
- [Way 1] 네트워크 연결 없어도 연결
<script src="../resources/js/jquery-3.6.3.min.js"></script>
- [Way 2] 네트워크 통해서 연결
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
💁 문서가 로드된 이후 jQuery를 실행하는 방법
(window.onload 속성과 같은 개념의 메소드)
- [Way 1]
$(document).ready(function(){});
- [Way 2]
$(function(){});
💁 jQuery 기본 형태
$('선택자').메소드명('속성', '속성값');
$(document).ready(function(){
});
// $(function(){}); : 위와 동일한 의미
$(function(){
$("*").css('color', 'red');
});
filter()
first()
last()
eq(n)
not()
text()
$(document).ready(function(){
console.log($(".test"));
// filter : 특정 기준과 일치하는 요소를 반환
// test 클래스 요소 중 짝수 인덱스(0, 2, 4) 반환
console.log($(".test").filter(":even")); // :even : 짝수에 해당하는 것을 필터링
$(".test").filter(":even").css({ background : "tomato", color : "white" });
// 함수를 매개변수로 하는 filter 메소드
$(".test").filter(function(){
return index % 2 == 1; // test 클래스 요소 중 홀수 인덱스는 true 리턴
}).css({background : "yellow", color : "white"});
});
// 선택 된 요소 중 제일 처음에 있는 요소
$("h4").first().css("font-size", "1.5rem");
// 선택 된 요소 중 제일 마지막에 있는 요소
// text 메소드 : 텍스트 노드를 가져오거나 변경
$("h4").last().text($("h4").last().text() + " : 마지막 요소"); // 소괄호 안의 $("h4").last().text()는 test-6를 의미
// $("h4").last().text() = setter / $("h4").last().text() = getter
// 인덱스 번호와 일치하는 요소
$("h4").eq(3).text($("h4").eq(3).text() + " : eq(3)으로 필터링");
// 인자 값과 일치하지 않는 요소만 리턴
$("h4").not(".test").css({ background : 'pink', color : 'white' }); // $("h4").not(".test")는 tese-5를 의미
parent()
parents()
parentsUntil()
🙋 선택 된 요소의 상위 요소들을 선택할 수 있는 메소드
- 선택 된 요소의 바로 위 상위 요소들을 선택할 수 있는 메소드
$('selector').parent()
- 선택 된 요소의 모든 상위 요소 리턴
매개변수가 있으면 매개변수와 일치하는 부모만 리턴
$('selector').parents([매개변수])
- 선택 된 요소부터 매개변수 요소까지의 범위의 요소 리턴
$('selector').parentsUntil(매개변수)
$(function(){
$(".test1 span").parent().css({ color : 'red', border : '2px solid red'}); // span의 바로 윗 부모만 선택
// $(".test1 li").parents().css("color", "blue"); // body 영역을 포함한 모든 부모 영역이 선택됨
$(".test1 li").parents("div").css("color", "blue"); // 부모인 div영역만 선택됨
$(".test1 span").parentsUntil("div").css("background", "lightgreen"); // div를 제외한 그 아래의 부모(ul)이 선택됨
});
children()
find()
🙋 선택 된 요소의 하위 요소들을 선택할 수 있는 메소드
- 선택 된 요소의 모든 자식 객체 리턴
매개변수가 있으면 매개변수와 일치하는 자식 객체만 리턴
$('selector').children([매개변수])- 선택 된 요소의 매개변수와 일치하는 모든 후손 객체 리턴
$('selector').find(매개변수)
$(function(){
$(".test2").children().css(style1); // 바로 아래의 자식인 div들만 선택
$(".test2").children().children().css(style2); // 그 아래(div)의 바로 아래의 자식인 ul과 p 선택
$(".test2").children().children("ul").css(style3); // 그 아래(div)의 바로 아래의 자식인 ul만 선택
$(".test2").find("li").css(style4); // 모든 자식들 중 li만 선택
$(".test2").find("span").css(style5); // 모든 자식들 중 span만 선택
})
siblings()
next()
nextAll()
nextUntil()
prev()
prevAll()
prevUntil()
🙋 같은 레벨에 있는 요소를 선택할 수 있는 메소드
- 선택 된 요소와 같은 레벨에 있는 모든 요소 리턴
매개변수가 있으면 같은 레벨에 있는 요소 중 매개변수와 일치하는 모든 요소 리턴
$('selector').siblings([매개변수])
- 선택 된 요소의 같은 레벨 중 선택 된 요소 다음 한 개 요소 리턴
$('selector').next()
- 선택 된 요소의 같은 레벨 중 선택 된 요소 다음의 모든 요소 리턴
$('selector').nextAll()
- 선택 된 요소의 같은 레벨 중 선택 된 요소 다음부터 매개변수 이전까지의 모든 요소 리턴
$('selector').nextUntil(매개변수)
- 선택 된 요소의 같은 레벨 중 선택 된 요소 이전의 한 개 요소 리턴
$('selector').prev()
- 선택 된 요소의 같은 레벨 중 선택 된 요소 이전의 모든 요소 리턴
$('selector').prevAll()
- 선택 된 요소의 같은 레벨 중 선택 된 요소 이전부터 매개변수 이전까지의 모든 요소 리턴
$('selector').prevUntil(매개변수)
$(function(){
$(".wrap h2").siblings().css(style1); // h2의 모든 형제들 선택
$(".wrap h2").siblings("p").css(style2); // h2의 형제들 중 p 태그만 선택
$(".wrap h2").next().css(style3); // h2의 형제들 중 h2의 바로 뒤 h3 태그만 선택
$(".wrap h2").nextall().css(style4); // h2 다음의 모든 형제들 선택
$(".wrap h2").nextUntil("p").css(style5); // h2와 p사이의 모든 형제들 선택
$(".wrap h2").prev().css(style5); // h2 바로 앞의 형제 선택
$(".wrap h2").prevAll().css(style4); // h2 앞의 모든 형제들 선택
$(".wrap h2").prevUntil("p").css(style3); // h2 앞의 형제들 중 p 선택
});
html()
💁♀️ 선택 된 요소의 content 영역을 리턴하거나 설정하는 메소드로 getter 사용 시 해당 요소를 태그까지 포함하여 얻어오고 setter로 사용 시 작성 된 html 태그를 실제 태그로 인식 시킴
$(document).ready(function(){ // getter 역할
let tmp = $("#test1").html();
console.log(`html 메소드 리턴 값 : ${tmp}`);
$("#test2").html(tmp);
$("#test2").children("a").attr("href", "https://www.naver.com");
});
$(function(){
// html 메소드의 콜백 함수에는 선택된 요소 목록의 현재 요소 인덱스,
// 이전 컨텐츠 값이라는 두 값이 전달
// 콜백 함수에서 설정할 값으로 사용할 문자열을 리턴
$(".testClass1").html(function(index, html){ // index : 인덱스 값 / html : 문자(div1)
return `<h1>이전 값 : ${html}, index : ${index}</h1>`;
});
});
💁♀️ 선택 된 요소의 content 영역을 리턴하거나 설정하는 메소드로 getter로 사용시 태그는 무시하고, setter로 사용 시 html 태그를 문자 자체로 인식
$(function(){
let tmp = $("#test3").text();
console.log(`text 메소드 리턴 값 : ${tmp}`); // <a>가 무시됨
$("#test4").text("<a>구글로 이동</a>"); // <a>를 문자열로 취급
})
$(function(){
$(".testClass2").text(function(index, text){ // index : 인덱스 값 / text : 문자(div1)
return `<h1>이전 값 : ${text}, index : ${index}</h1>`;
});
})
append()
prepend()
after()
before()
💁♀️ 선택자 요소를 기준으로 매개변수에 작성 되어진 생성 된 요소를 추가
$(A).append(B)
: A 요소 내 뒷 부분에 B를 추가
$(A).prepend(B)
: A 요소 내 앞 부분에 B를 추가
$(A).after(B)
: A 요소 뒷 부분에 B를 추가
$(A).before(B)
: A 요소 앞 부분에 B를 추가
setInterval()
clearInterval()
$(function(){
// setInterval 사용하여 1초마다 B, C, D, E 삽입
let arr = ['B', 'C', 'D', 'E'];
let index = 0;
let timer = setInterval(function(){ // timer 변수에 setInterval의 id값을 저장
let html = `<span>${arr[index++]}</span>`;
$("#add1").append(html);
$("#add2").prepend(html);
$("#add3").after(html);
$("#add4").before(html);
if(index > 3) clearInterval(timer); // 1초마다 돌아가는 Interval 중지
}, 1000);
})
appendTo()
prependTo()
insertAfter()
insertBefore()
💁♀️ 생성 된 요소를 매개변수로 지정한 선택자 요소에 추가
(part 1의 메소드와 선택자, 생성 구문의 순서가 반대)
$(A).appendTo(A)
: B를 A 요소 내 뒷 부분에 추가
$(A).prependTo(A)
: B를 A 요소 내 앞 부분에 추가
$(A).insertAfter(A)
: B를 A 요소 뒷 부분에 추가
$(A).insertBefore(A)
: B를 A 요소 앞 부분에 추가
$(function(){
// setInterval 사용하여 1초마다 B, C, D, E 삽입
let arr = ['B', 'C', 'D', 'E'];
let index = 0;
let timer = setInterval(function(){ // timer 변수에 setInterval의 id값을 저장
$($("<span>").text(arr[index])).appendTo("#add5")
$($("<span>").text(arr[index])).prependTo("#add6")
$($("<span>").text(arr[index])).insertAfter("#add7")
$($("<span>").text(arr[index])).insertBefore("#add8")
index++;
if(index > 3) clearInterval(timer); // 1초마다 돌아가는 Interval 중지
}, 1000);
})
clone()
clone([true|false])
: html 요소를 복사하는 메소드로 매개변수로 이벤트 복사 여부를 지정 (기본 값은 false)
$(function(){
// 마우스 오버 이벤트 추가
$("#item1").hover(function(){
// 마우스가 올라갔을 때,
$(this).addClass("lime");
}, function(){
// 마우스가 내려갔을 때,
$(this).removeClass("lime");
});
// 버튼 클릭 이벤트
$("#clone").click(function(){
// $("#item1").clone().appendTo("#clone-test"); // true를 전달하지 않으면 클론들에는 hover 이벤트 적용 X
$("#item1").clone(true).appendTo("#clone-test"); // 클론들도 hover 이벤트 적용 O
});
})
empty()
: 모든 자식 요소 제거
remove()
: DOM 요소 잘라내기. 연관 된 이벤트도 모두 삭제
detach()
: DOM 요소 잘라내기. 연관 된 이벤트 모두 보관
$(function(){
$('#item2').hover(function(){
// 마우스를 올렸을 때
$(this).addClass("lime");
}, function(){
// 마우스를 내렸을 때
$(this).removeClass("lime");
});
$("#empty").click(function(){
$("#remove-test").empty();
});
$("#remove").click(function(){ // hover 이벤트 사라짐
let elem = $("#item2").remove();
$("#result").html(elem);
})
$("#detach").click(function(){ // hover 이벤트 유지
let elem = $("#item2").detach();
$("#result").html(elem);
});
});
객체나 배열을 관리하는 for in문과 비슷한 메소드로 객체나 배열의 요소를 검사
- [Way 1]
$.each(object, function(index, item){})
- [Way 2]
$('selector').each(function(index, item){})
$(function(){
const arr = [
{ name : '네이버', link : 'http://www.naver.com'},
{ name : '구글', link : 'http://www.google.com'},
{ name : 'w3school', link : 'http://www.w3shcools.com'}
];
let html = '';
$.each(arr, function(index, item){
html += `<h2><a href='${item.link}'>${item.name}</a></h2>`;
});
$("#area1").html(html);
});
$(function(){
// wrap의 자식 요소 하나하나에 콜백함수 전달
$("#wrap").children().each(function(index, item){
$(this).addClass("highlight_" + index);
});
});
💁♀️ 문서 객체의 특징을 판별하는 메소드로, 매개변수로 선택자를 입력하고 선택한 객체가 선택자와 일치하는지 판단하여 boolean을 리턴
$(function(){
$("h3").each(function(){
if($(this).is(".test")) // test 클래스인지 판단
$(this).css({ background : 'orangered', color : 'white'});
});
});
많은 자바스크립트 라이브러리가 '$' 기호를 함수, 변수로 사용하고 있기 때문에 jQuery 라이브러리와 충돌하는 경우가 종종 존재.
또는 다른 버전의 jQuery와의 충돌도 있을 수 있음. 이를 방지하기 위해 noConflict 메소드를 통해 '$' 대신 새로운 alias(별칭)을 부여하고 사용 가능
// 이제 이 문서에서 jQuery를 나타내던 '$'는 사용할 수 없고 이제 '$'대신 jq를 사용해야함
// let jq = $.noConflict();
jq(function(){ // 위를 주석하면 이제 jp는 읽히지 않음
jq("#ncTest").css("color", "red");
})
on()
off()
💁♀️ 요소 객체에 이벤트 발생 시 연결 될 이벤트 핸들러를 지정하는 메소드
$('selector').on('이벤트명', '이벤트 핸들러')
: 현재 존재하는 문서 객체에만 이벤트를 연결
$('selector').off('이벤트명' [, '이벤트 핸들러'])
: on으로 연결 된 이벤트를 제거
$('#test1').on('click', function(){
console.log(event.target);
console.log($(this).text());
});
// 여러 개의 이벤트를 객체로 전달하여 등록 가능
$("#test1").on({ mouseenter : function(){
$(this).css("background", "yellowgreen").text("마우스 올라감");
}, mouseleave : function(){
$(this).css("background", "yellow").text("마우스 내려감");
}, click : function(){
$(this).off('mouseenter').off('mouseleave')
.css("background", "orangered").text("이벤트 제거됨");
}});
$('selector').on(events, selector, handler)
선택자를 기준으로 매개변수로 전달 된 selector에 지정한 이벤트 발생 시
해당 핸들러를 동적으로 적용시켜 이벤트 처리 가능
function add() {
$("#wrap").append('<h2>클릭으로 인해 추가됨</h2>');
}
// 해당 코드가 수행될 때 문서에 존재하는 h2 요소에게만 이벤트가 연결
// $("h2").on('click', add);
// 문서 내에 동적으로 추가 된 h2 요소에게도 이벤트가 연결
$(document).on('click', 'h2', add);
one()
💁♀️ 이벤트를 단 한번만 동작시키고자 할 때 사용
$("#test2").one('click', function(){
alert('처음이자 마지막 이벤트 발생!');
});
trigger()
💁♀️ 특정 이벤트나 기본 이벤트를 강제로 발생시키는 메소드로 사용자 정의 이벤트 발생 시 사용. 이벤트 발생 시 인자 값 전달 가능
$(function(){
let cnt = 0;
$("#trg").on('click', function(){
$("#cnt").text(++cnt);
});
$("#increment").on('click', function(){
// #trg의 click 이벤트 핸들러를 요청
$("#trg").trigger('click');
// #increment를 클릭해도 위의 클릭 이벤트 핸들러를 호출하기 때문에 count됨
});
});
trigger 메소드는 실제 이벤트가 발생하는 것이 아니라 이벤트 핸들러를 호출하는 것. 따라서 아래의 경우 a 태그의 링크로 실제 이동 X
<a href="https://www.naver.com" id="goNaver" onclick="justClicked()">네이버로 이동</a>
<button id="btnTrg">trigger를 통한 a 태그 클릭</button>
function justClicked() {
console.log('just Clicked!!');
}
$("#btnTrg").on('click', function(){
$("#goNaver").trigger('click');
});
// 이벤트 핸들러를 호출할 뿐, 이벤트 객체까지 발생하는 것이 아니므로, 링크로 이동 X
mouseenter
/mouseleave
: 자식 요소 접근시에는 이벤트 핸들링 X
mouseover
/mouseout
: 자식 요소 접근 시에도 이벤트 핸들링 O
$(function(){
// $(".o1").mouseenter();
// $(".o1").mouseleave();
// $(".o1").mouseenter().mouseleave(); // 위 두 코드를 이렇게 합칠 수 있음
$(".o1").mouseenter(function(){
$("#output1").text($("#output1").text() + "ENTER!");
}).mouseleave(function(){
$("#output1").text($("#output1").text() + "LEAVE!");
});
$(".o2").mouseover(function(){ // 자식 요소에 접근했을 때도 이벤트 발생
$("#output2").text($("#output2").text() + "OVER!");
}).mouseout(function(){
$("#output2").text($("#output2").text() + "OUT!");
});
});
keydown
: 키보드가 눌려질 때
keypress
: 글자가 입력될 때(기능키 사용 불가)
keyup
: 키보드 떼어질 때
$(function(){
$("#inputTest").keydown(function(e){
console.log(`keydown : ${e.key}`);
}).keypress(function(e){
console.log(`keypress : ${e.key}`);
}).keyup(function(e){
console.log(`keyup : ${e.key}`);
});
});
regExp
<label for="memberId">아이디 : </label>
<input type="text" name="memberId" id="memberId">
<span id="idCheck"></span>
$(function(){
$("#memberId").keyup(function(){ // keyup : key를 뗄 때마다 동작
const regExp = /^[a-z][a-z\d]{5,11}$/;
// val() : value를 가져오는 jQeury의 함수
if(regExp.test($(this).val())) {
$("#idCheck").text("사용 가능한 아이디 형식입니다!")
.css({ color : 'green', 'font-weight' : 'bolder'});
} else {
$("#idCheck").text("사용 불가능한 아이디 형식입니다!")
.css({ color : 'red', 'font-weight' : 'bolder'});
}
});
})
focus()
blur()
change()
select()
focusin()
focusout()
submit()
$(function(){
// 입력 양식 관련 이벤트 감지 테스트
$("#name").focus(function(){
console.log('FOCUS');
}).blur(function(){
console.log('BLUR');
}).change(function(){
console.log('CHANGE');
}).select(function(){
console.log('SELECT');
});
// focusin, focusout : 해당 요소와 자식 요소가 포커스를 가지면 이벤트 발생
// focus, blur는 버블링 발생 X
$("td").focusin(function(){
console.log('FOCUSIN');
}).focusout(function(){
console.log('FOCUSOUT');
});
// 이름에 두 글자 이상의 한글을 작성했는지 확인
$("#name").change(function(){ // change : 입력하고 focus를 잃으면 발생
const regExp = /^[가-힣]{2,}$/;
if(regExp.test($(this).val())) {
$("#nameresult").text("정상 입력").css("color", "green");
} else {
$("#nameresult").text("한글로 두 글자 이상 입력").css("color", "red");
}
});
// 입력 양식 제출 전 발생하는 submit 이벤트
$("form").submit(function(){
// confirm 창에서 취소를 누른 경우, submit 기본 이벤트 제거
if(!confirm('폼을 제출하시겠습니까?'));
return false;
});
});
💁♀️ Effect란,
페이지에 애니메이션 효과를 만들기 위한 메소드
$('selector').메소드명([speed], [easing], [callback])
- speed : 실행 속도(ms) / 숫자 or slow/fast
- easing : 변경되는 지점별 속도 / linear, swing
- callback : 메소드 실행 후 실행할 함수
show()
hide()
toggle()
💁 문서 객체를 크게 하며 보여주거나 작게 하며 사라지게 함
$(function(){
$('#show').click(function(){
$("#pika").show(1000);
});
$('#hide').click(function(){
$("#pika").hide(1000);
});
})
// 토글 사용
$(function(){
$("#toggle").click(function(){
$("#dog").toggle(3000);
});
});
slideUp()
slideDown()
$(function(){
$(".menu").click(function(){
// 클릭 이벤트가 발생한 div의 다음으로 오는 p가 none일 경우(안 열려있을 경우)
if($(this).next("p").css("display") === 'none') {
$("p.contents").slideUp(); // contents클래스를 가진 p들을 닫고,
$(this).next("p").slideDown(); // sildeDown(아래로 연다)
} else { // none이 아닐 경우(열려있을경우)
$(this).next("p"),slideup(); // sildeup(위로 닫는다)
}
// 열리지 않는 모든 탭이 열림 (다른 걸 열어도 닫히지 않고 유지상태)
// $(this).next("p").slideToggle();
})
});
fadeIn()
fadeOut()
fadeTo()
fadeToggle()
fadeIn
: 점점 진하게 변하면서 보여지는 효과
fadeOut
: 점점 희미하게 변하면서 사라지는 효과
fadeTo
: 설정한 값까지 희미해지는 효과 (opacity 값으로 투명도 조절)
$(function(){
$("#fadeIn").click(function(){
$("#diningtable").fadeIn(2000);
});
$("#fadeOut").click(function(){
$("#diningtable").fadeOut(2000);
});
$("#fadeToggle").click(function(){
$("#diningtable").fadeToggle(2000, function(){
alert("토글 성공^^!") // 토글이 완료된 후 alert창이 뜨는 콜백 함수
});
});
$("#flower").hover(function(){
$("#flower").fadeTo(3000, 0.5);
}, function(){
$("#flower").fadeTo(3000, 1);
});
});