본문 바로가기
WEB

jQuery와 예제

by 둥바 2022. 7. 4.

JQUERY 

- 자주 사용되는 자바스크립트 라이브러리

- write less, do more 라는 캐치 프레이즈 내세움

- https://jquery.com/download/ 에서 다운로드 Download the compressed, production jQuery 3.x.x 선택 후 마우스 우클릭하여 "다른이름으로 링크 저장" 후 이클립스에 복사

 

jQuery 버전

- 1.x버전 : 모든 구브라우저 지원

- 2.x버전 : Internet Esxplorer 6,7,8 지원X

- 3.x버전 : 2014년부터 개발, 더 빠르고 풍부한 API,대부분의 최신브라우저만 지원

 

jQuery 사용방법

- 다운로드 받아서 사용

<script src="jquery-3.x.x.js"></script>

- 다운로드 받지 않고 사용할 경우 (Content Delivery Network 연결방식)

https://code.jquery.com/에 에 접속하여 jQuery 3.x의 minified를 클릭 -> cdn접속 정보가 나오면 복사해서 사용

<script src="http://code.jquery.com/jquery-3.x.x.js"></script>

 

일반적인 jQuery 구조

DOM이 로딩 완료(onload 함수사용과 비슷)되면 jQuery함수가 자동으로 실행된다.

 

1) 정식표현

$(document).ready(function() {
    $(selector).함수(){ //실행 코드
  });
});
  • $ : jQuery에서 엘리먼트(태그) 접근시 사용
  • (selector) : 선택자로서 HTML 객체(태그) 선택
    • $("#name") : id가 name인 태그 선택
    • $( ) 안에는 태그명, 태그의 id 속성값, class 속성값이 올 수 있다.
    • 엘리먼트명 사용 : $("p")
    • id 속성값 사용 : $("#test")
    • class 속성값 사용 : $(".t1")
  • 함수() : 해당 객체에서 수행할 동작

2) 약식표현

$(function(){
  //실행 코드
});

 

 

이벤트 처리

$(선택자).이벤트(함수); //한개의 이벤트 처리

$(선택자).bind(이벤트:함수,이벤트:함수,...); //여러개의 이벤트 처리

 

이벤트 종류(자바스크립트의 on이라는 이름이 빠짐)

- click

- mouseover

- focus

- blur

 

애니메이션 효과

show("slow"),show("fast")

hide() 숨기기

toggle() show/hide를 교대로

animate() 애니메이션 효과

stop() 애니메이션 중지

fadeIn() 페이드인 효과

fadeOut() 페이드아웃

slideUp() 슬라이드 올림

slideDown() 슬라이드 내림

 

JQuery를 이용한 DOM 변경

- $(선택자).text() : 텍스트 가져옴

- $(선택자).text("변경 내용") : 텍스트 변경

- $(선택자).html() : html코드 가져옴

- $(선택자).html("변경 내용") : html코드 변경

- $(선택자).val() : 입력필드의 값 가져옴

- $(선택자).val("변경 내용") : 입력필드 값 변경

- $(선택자).attr("변경 속성") : 요소의 속성 가져오기

- $(선택자).append("추가 요소") : DOM 요소 추가

- $(선택자).remove() : DOM에서 삭제 처리

 

CSS 조작

- $(선택자).css("속성") : css속성 가져오기

- $(선택자).css("속성","값") : css속성값 변경

 

 

참고로, 일일히 script 에 <script src="../include\jquery-3.6.0.min.js"></script>를 붙이는 게 번거롭기 때문에

eclipse의 Window -> Preferences -> Web -> HTML files -> Editor -> Templates -> New HTML(html5)에 해당 스크립트를 복사해서 붙여주면, 앞으로 html을 생성할 때마다 해당 스크립트가 포함되어 생성된다.

 

 

선택자 예제

예제 1번 ) 태그를 누르면 사라지게 하는 애니메이션
현재 문서가 로딩 완료되면 자동으로 실행되는 함수 = 콜백함수
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Selector1</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
//현재 문서가 로딩 완료되면 자동으로 실행(콜백함수)
$(document).ready(function(){
	//<body onload="함수">와 같은 효과
	$("h2").click(function(){
		$(this).hide(); //클릭한 태그 숨겨짐
	});
});

</script>
</head>
<body>
	<h2>첫번째 h2</h2>
	<h2>두번째 h2</h2>
	<h2>세번째 h2</h2>
</body>
</html>

 

예제 2번 : 선택자를 통해 첫번째, 마지막 리스트의 배경색 변경
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>selector2</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
//정식 $(document).ready(function()으로 시작했겠으나,
//약식으로 표현하면 다음과 같다.
$(function(){
	//li의 첫번째 태그 스타일 변경 first-of-type
	$("li:first-of-type").css("background-color","yellow");
	//li의 마지막 태그 스타일 변경 last-of-type
	$("li:last-of-type").css("background-color","pink");
	$("li:last-of-type").css("font-size","20px");
});


</script>
</head>
<body>

<h1>탐색 선택자</h1>
<ul>
	<li>내용1</li><!-- 첫번째  -->
	<li>내용2</li>
	<li>내용3</li><!-- 마지막  -->
</ul>
<ul>
	<li>내용4</li><!-- 첫번째  -->
	<li>내용5</li>
	<li>내용6</li><!-- 마지막  -->
</ul>
</body>
</html>

 

예제 3번 : 3의 배수와, 뒤에서 2번째인 태그에 각각 배경색 넣기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function(){
	//태그의 3의 배수 nth-child(3n)
	$("li:nth-child(3n)").css("background-color","yellow");
	//끝에서 2번째
	$("li:nth-last-of-type(2)").css("background-color","pink");
});
//중첩되는 경우, 마지막이 덮어버림

</script>
</head>
<body>
	<h1>탐색 선택자</h1>
	<ul>
		<li>내용1</li>
		<li>내용2</li>
		<li>내용3</li>
		<li>내용4</li>
		<li>내용5</li>
		<li>내용6</li>
	</ul>
	<ul>
		<li>내용7</li>
		<li>내용8</li>
		<li>내용9</li>
		<li>내용10</li>
	</ul>
</body>
</html>

 

마우스 이벤트 예제

예제 1번 ) 마우스가 빠져나갈때, 마우스 클릭할 때, 마우스가 요소에 들어올 때 이미지 바뀌는 이벤트
$("요소").bind({ //하나의 요소에서 여러 이벤트를 한번에 사용할 때
이벤트 : 함수,
이벤트 : 함수
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>mouse1</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function(){
	$("img").mouseout(function(){//마우스가 빠져나갈 때
		$("img").attr("src","../image/i0075.jpg");
	//attr(속성,변경)
	});
	$("img").mouseover(function(){//마우스 요소에 올라갈 때
		$("img").attr("src","../image/i0076.jpg");
	});
	$("img").click(function(){//마우스 클릭 시에
		$("img").attr("src","../image/i0073.jpg");
	});
});
//하나하나 처리하면 위와 같이 처리,
//한 번에 여러 이벤트 처리하는 방법
//선택자.bind({이벤트:함수,이벤트:함수})
$(function(){
	$("img").bind({
		mouseout : function(){
			$("img").attr("src","../image/i0075.jpg");
		},
		mouseover : function(){
			$("img").attr("src","../image/i0076.jpg");
		},
		mouseover : function(){
			$("img").attr("src","../image/i0073.jpg");
		}
	});
});
</script>
</head>
<body>
 <img src="../image/i0075.jpg">

</body>
</html>

 

예제 2번 : 해당 영역에 마우스를 올리면 마끼가 나타나고, 숫자가 올라가는 처리
text("값") : 글자처리(변경), innerText(html 해석안함)
html("값") : html 내용 해석, innerHTML(html 해석함)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>mouse2</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function(){
	var i = 0;//전역변수
	$("div.out").mouseover(function() {
		$("p:first").html("<marquee>mouse over</marquee>");
		$("p:last").text(++i);//두번째 p태그 0값이 계속 1씩 증가처리됨
		//text("값") : 글자처리(변경), innerText(html을 해석하지 않음)
		//html("내용") : html 내용해석, innerHTML(html을 해석)
	});
	
	$("div.out").mouseout(function() {
		$("p:first").text("마우스를 여기로 움직이세요.");
	}); 
});


</script>
</head>
<body>
<div class="out">
	<p>마우스를 여기로 움직이세요.</p>
	<p>0</p>
</div>
<div>
두번째 div(기능없는 비교용 문자)
</div>
</body>
</html>

 

 

예제 3번 : 마우스 이동에 따라 x,y좌표값 바뀜
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).mousemove(function(e){
	console.log(e);
	//e : 마우스이벤트 참조변수
	//pageX : X좌표값, pageY : Y좌표값
	$("#log").html("<h2 style='color:red;'>x:"+ e.pageX +",y:"+ e.pageY +"</h2>");
});
</script>
</head>
<body>
<div id="log">

</div>
</body>
</html>

 

포커스 이벤트 

예제 1번 ) 입력필드에 포커스가 될 때 CSS와 포커스 잃을 때 CSS 다르게
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>focus_event</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function(){
	$("input").focus(function(){
		//포커스 이벤트
		$(this).css("background-color","yellow");
		$(this).css("border","3px dotted red");
	});
	$("input").blur(function(){
		//입력포커스를 잃을 때 이벤트(blur)
		$(this).css("background-color","white");
		$(this).css("border","1px solid black");
	});
});


</script>
</head>
<body>
	아이디:<input type="text" name="name"><br>
	비밀번호:<input type="text" name="pwd">
	
</body>
</html>

 

 

애니메이션 이벤트

예제 1번 ) hide,show,fadein,fadeout,toggle,slideup,slidedown,animate 활용
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function(){
	//show버튼 누르면 보이게
	$("#btnShow").click(function(){
		$("#img1").show("fast");
		//빠르게 보임
	});
	//hide버튼 누르면 숨기게
	$("#btnHide").click(function(){
		$("#img1").hide("fast");
	});
	//toggle버튼 누르면 숨김,보임 번갈아서 교대실행
	$("#btnToggle").click(function(){
		$("#img1").toggle("fast");
	});
	//animate버튼 누르면 img1 이동
	$("#btnAnimate").click(function(){
		$("#img1").animate({
			left: '500px',
			top: '200px',
			opacity: '0.5'
		},5000);
	});
	//fadein누르면 
	$("#btnFadein").click(function(){
		$("#img1").fadeIn(5000,function(){
			$("#img2").fadeIn("slow");
		});
	});
	//fadeout누르면
	$("#btnFadeout").click(function(){
		$("#img1").fadeOut("slow");
	});
	//슬라이드 다운
	$("#btnSlidedown").click(function(){
		$("#img1").slideDown("slow");
	});
	//슬라이드업
	$("#btnSlideup").click(function(){
		$("#img1").slideUp("slow");
	});
	//페이드아웃.슬라이드다운.쇼 멀티로
	$("#btnChain").click(function() {
		$("#img1").show().fadeOut("slow").slideDown("slow");
	});
});
</script>

<style type="text/css">
#img1 {
	display: none; /* 숨김(자리차지X) */
	position: relative;
}

#img2 {
	display: none;
}
</style>
</head>
<body>
 <button id="btnShow">표시</button>
 <button id="btnHide">숨김</button>
 <button id="btnToggle">toggle</button>
 <button id="btnAnimate">애니메이션</button>
 <button id="btnFadein">페이드인</button>
 <button id="btnFadeout">페이드아웃</button>
 <button id="btnSlidedown">slide down</button>
 <button id="btnSlideup">slide up</button>
 <button id="btnChain">여러 효과</button>
 <hr>
 <img id="img1" src="../image/image.png">
 <img id="img2" src="../image/google.png">
</body>
</html>

 

 

JQUERY 이용한 DOM 변경 예제

예제 1번 ) text와 html 차이 : html태그 해석 여부
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>domEx</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function(){
	//선택자.html() : 내용을 가져온다.(get)
	//선택자.html("내용"); 태그 내부 내용 변경(set)
	
	
	$("#text").click(function(){
		$("#target").text("<marquee>변경된 내용입니다.</marquee>");
		alert($("#target").text());//alert창에 내용만 get해옴
	});
	//text는 태그 써도 해석안됨(텍스트)
	//반면에 html태그는 해석 됨
	$("#html").click(function() {
		$("#target").html("<marquee>변경된 내용입니다.</marquee>");		
		alert($("#target").html());
	})
});

</script>
</head>
<body>
	<h2>jQuery를 사용한 DOM 변경</h2>
	<p id="target">
	이것은 <strong>하나의</strong> 단락입니다.
	</p>
	<button id="text">버튼1</button>
	<button id="html">버튼2</button>
</body>
</html>

 

예제 2번 : 텍스트 입력필드의 값 이용, 이미지와 속성 변경
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function(){
	$("#button1").click(function(){
		var name = $("#name").val();
		alert(name);
		name = prompt("이름 입력하세요.","이무기");
		$("#name").val(name);//태그의 value 변경
		$("#img1").attr("src","../image/apple.png");
		//2개 이상의 속성을 바꿀 경우 attr ({})로 묶는다.
		$("#img1").attr({
			"width" : "100px",
			"height" : "100px"
		});
		var img = $("#img1").attr("src"); //src속성 값 읽기
	});
});

function check(){
	var name=document.getElementById("name").value;
	alert(name);
}

</script>
</head>
<body>
이름 : <input id="name" value=""><br>
<img id="img1"src="../image/tomato.jpg"><br>
<button id="button1">확인</button>
</body>
</html>

 

예제 3번 : append, prepend,after,before,remove,empty 활용 예제
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>append_remove</title>
<script src="../include\jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function(){
	$("#button1").click(function(){
		$("ul").append("<li>레몬</li>");//마지막에 추가
	});
	$("#button2").click(function(){
		$("ul").prepend("<li>레몬</li>");//해당 요소의 시작부분에 추가
	});
	$("#button3").click(function(){
		$("h2").after("<marquee>hello</marquee>");//h2뒤에 추가
	});
	$("#button4").click(function(){
		$("h2").before("<img src='../image/tomato.jpg'>");//h2 앞에 추가
	});
	$("#button5").click(function(){
		$("#div1").remove(); //모두 제거
	});
	$("#button6").click(function(){
		$("#div1").empty(); //div 유지, 컨텐츠 제거
	})
});


</script>
</head>
<body>
 <div id="div1" style="border: 1px solid red; height: 300px;">
  <h2>과일 목록</h2>
  <ul>
   <li>사과</li>
   <li>포도</li>
   <li>배</li>
  </ul>
  
  <button id="button1">append</button>
  <button id="button2">prepend</button>
  <button id="button3">after</button>
  <button id="button4">before</button>
  <button id="button5">remove</button>
  <button id="button6">empty</button>
  </div>
</body>
</html>