Jquery 예제 - jquery yeje

[  jQuery 란? ]

: javaScript를 편리하게 사용할 수 있도록 해주는 Java Script Library이다.

- javascript에 jQuery를 쓰면 웹 호환성이 좋아진다!

jQuery 사용을 선언하기

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<head>와 </head> 사이에 삽입해준다.

jQuery 시작 하기

jQuery(document).ready(function(){
  // process..
});

$(document).ready(function(){
   // process.. 
});

$(document).ready(callback 함수) = jQuery와 $는 같은 의미이다
document가 준비된 시점에 (=메모리에 로딩 시에) 익명함수가 실행되고, 
이 익명함수는 현 페이지에서 필요한 이벤트 행위를 일괄적으로 등록한다.

- jQuery 이벤트 메서드 중 하나

• 문서의 DOM 요소들을 조작 할 수 있는 시점에서 호출

• javascript의 load 이벤트와 비슷

jQuery 기분 문법 -Selector (선택자)

  • $(‘a’) – page 내 모든 <a>
  •  $(‘div a’) – page 내 <div> 하위에 있는  <a>
  • $(‘#test’) – id가 test인 태그
  • $(‘.btn’) – class가 btn인 모든 태그
  • $(‘tr:odd’) - <tr> 태그들 중 홀수번째들
  • $(‘tr:last tr:last’) – 문서내의 마지막 <tr> 
  • $(‘b:contains(‘hi’)) – hi를 content로 가진 b태그
  • $(‘div:has(‘ul’) - <ul> 을 가진 <div> 태그 
  • $(‘input:checkbox’) – input태그중 checkbox
  • $(‘td nth-child(2n)’) –2의 배수 번째 <td>

Content/DOM 변경 및 조회 메소드

  • html()
    – 선택요소의 html 내용을 가져옴. innerHTML과 동일
  • html(value)
    – 선택요소에 인수로 받은 value를 넣는다.
    – value내에 html태그가 있는 경우 태그로 들어간다.
  • text()
    – 선택요소 내의 html태그 요소를 제외한 내용을 가져옴.
    innerText innerText와 동일.
  • text(value)
    – 선택요소 내에 인수로 받은 value를 넣는다.
    – value내의 html태그도 text로 들어간다.
  • val()
    – input 태그의 value 값을 조회
  • val(value)
    – 인수로 받은 value를 input 태그의 value 값을 설정

사용 예시

[ 목차 ] : 클릭하여 목차 이동

1. jQuery ready & 이벤트 등록 기본 - Tag

$("tag")로 이벤트 등록

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery basic</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	//jQuery의 ready함수는 document가 준비되는 시점에 실행된다.
/* 	jQuery(document).ready(function() {
		alert("jquery");
	}); */
	// jQuery와 $는 같은 표현이다
	$(document).ready(function() {
		//alert("jquery"+ document.getElementById("ts"));
		
		//ready 시점에 현 페이지의 이벤트를 등록한다.
		// 이벤트 : a tag를 클릭했을 때, 자신의 텍스트를 alert
		$("a").click(function () {
			alert($(this).text());
		})
	});
</script>
</head>
<body>
<div class="container">
	<h3>jQuery Basic</h3> <br>
	<span id="ts">test span</span>
	
	<ul>
		<li><a href="#">test1</a>
		<li><a href="#">test2</a>
		<li><a href="#">test3</a>
	</ul>
<!-- <script type="text/javascript">
		alert(document.getElementById("ts"));
	 </script>
 -->
</div>
</body>
</html>
Jquery 예제 - jquery yeje
Jquery 예제 - jquery yeje

2.  jQuery ready & 이벤트 등록 기본 - Input

$(":type")로 이벤트 등록

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery Basic</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	//document가 준비된 시점에 (=메모리에 로딩 시에) 익명함수가 실행되고, 
	//이 익명함수는 현 페이지에서 필요한 이벤트 행위를 일괄적으로 등록한다.
	$(document).ready(function() {
		//이번트 등록
		// : $(:button) -> jQuery 필터로 선택, type=button을 선택한다.
		$(":button").click(function() {
			alert($(this).val() + "번이 클릭했다!");
		});
	});
</script>
</head>
<body>
<div class="container">
	<input type="button" value="버튼 1"><br>
	<input type="button" value="버튼 2"><br>
	<input type="button" value="버튼 3"><br>
</div>
</body>
</html>
Jquery 예제 - jquery yeje

3. Class Seletor 이용 + Confirm 적용 

$(".class")로 이벤트 등록

: 다음과 네이버는 이벤트 적용이 되고, 구글은 바로 이동이된다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
	$(document).ready(function() {
		$(".ct").click(function () {
			//alert("클릭");
			
			//취소누르면 return
			return confirm($(this).text()+" 이동하시겠습니까?");
		});
	});
</script>
</head>
<body>
<div class="container">
	<a href="http://daum.net" class="ct">다음넷으로</a><br>
	<a href="http://naver.com" class="ct">네이버로</a><br>
	<a href="http://google.com">구글로</a><br>
</div>
</body>
</html>
Jquery 예제 - jquery yeje
Jquery 예제 - jquery yeje
Jquery 예제 - jquery yeje

4.  특정대상 골라서 event 주기 - id

$("#id")로 이벤트 등록

> text 적용 시

$("#id").text($(this).val());

> html tag 적용 시

$("#id").html("<html tag>" + $(this).val() + "</html tag>");

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery Basic</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		//id가 btn2인 대상을 선택해서, 이벤트 적용
		$("#btn2").click(function() {
			alert($(this).val());
		});
		
		//id가 btn3인 대상을 선택해서, 이벤트 적용
		// : 자신의 value를 <span id="resultView"> 영역에 출력
		$("#btn3").click(function() {
			//alert($(this).val());
			//$("#resultView").text($(this).val());
			
			//innerHTML 형식으로 html tag 적용 : html()
			$("#resultView").html("<font color=blue>"+ $(this).val() + "</font>");
		});
	});
</script>
</head>
<body>
<div class="container">
	<br><br>
	<input type="button" value="Test 1: 이벤트 적용 X"><br><br>
	<input type="button" value="Test 2: 값(value) 출력" id="btn2"><br><br>
	<input type="button" value="Test 3: 값(value)를 span에 출력" id="btn3"> : 
	
	<span id="resultView">span 영역</span>
</div>
</body>
</html>

> 1번 클릭하면, 아무 이벤트 X

Jquery 예제 - jquery yeje

> 2번 클릭하면 alert이 뜸 

Jquery 예제 - jquery yeje

> 3번 클릭하면 span에 내용 나옴

Jquery 예제 - jquery yeje

5.  class tag Selector 적용

$(".class tag")로 이벤트 등록

> class = food의 li tag 에만 이벤트 적용

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
	.a{
		background-color: yellow;
	}
	
	.b{
		background-color: lime;
	}
</style>
<title>jQuery CSS 선택</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		
		// food class 이하의 li 태그들을 대상으로
		// 이벤트를 적용
		$(".food li").click(function() {
			alert($(this).text());
		});
		
	});
</script>
</head>
<body>
<div class="container">
<ol class="a food">
	<li>바나나</li>
	<li>사과</li>
	<li>포도</li>
</ol>

<ol class="food b">
	<li>요거트</li>
	<li>치즈케이크</li>
	<li>크림치즈</li>
</ol>

<ol>
	<li>LA</li>
	<li>New York</li>
	<li>Washington</li>
</ol>
</div>
</body>
</html>

food class에 속하는 li를 클릭했을 때만, alert 반응이 있다.

Jquery 예제 - jquery yeje

6.  Selector 대상이 여러 개일 경우

$("selector,selector ..  ")로 이벤트 등록

> 1. id가 "testBtn"일 경우, 클릭하면 자신의 value를 alert으로 출력

> 2. class가 "student"인 경우, 클릭하면 id가 result인 영역에 자신의 text 출력

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$(document).ready(function () {
		
		//1. id가 testBtn일 경우, 클릭하면 자신의 value를 alert으로 출력
		$("#testBtn").click(function() {
			alert($(this).val());
		});
		
		//2. class가 "student"인 경우, 클릭하면 id가 result인 영역에 자신의 text 출력
		//   셀렉터를 , 로 이어서 둘 다 출력되도록 함
		$(".student, .teacher").click(function() {
			//alert($(this).text());
			$("#result").html("<font color=blue>"+ $(this).text()+ "</font>");
		});
		
	});
</script>
</head>
<body>
<div class="container">
	<input type="button" value="selector 연습 1" id="testBtn"><br><br>
	
	<div class="student">파프리카</div>
	<div class="teacher">오렌지</div>
	<div class="student">자몽</div><br>
	<hr>
	<div id="result"></div>
</div>
</body>
</html>

id가 testBtn인 버튼을 클릭했을 때, alert 반응이 온다.

Jquery 예제 - jquery yeje

class가 student에 속하는 div(파프리카, 자몽)를 클릭했을 때만, div result에 출력이 된다.

(but, ' , ' 를 통해 teacher class도 출력이 되도록했다!)

Jquery 예제 - jquery yeje

7.  이미지 조정

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		//사진 감추기
		$("#hideBtn").click(function() {
			//hide(시간, 후속작업)
			$("#imgView").hide(2000, function() {
				$("#stateInfo").html("<font size=7 color='lime'>"
						+"밀크 없다!"+"</font>");
			});
		});
		
		//사진 보기
		$("#showBtn").click(function() {
			$("#imgView").show(2000);
		});
		
	});
</script>
</head>
<body>
<div class="container">
	<img src="milk.jpg" id="imgView" height="500px" width="400px">
	<input type="button" value="사진 감추기" id="hideBtn">
	<input type="button" value="사진 보기" id="showBtn">
	
	<hr>
	
	<span id="stateInfo">
		<font size="7" color="green">밀크 있다!</font>
	</span>
</div>
</body>
</html>

> 1_1. '사진 감추기' : 사라지는 중

Jquery 예제 - jquery yeje

> 1_2. 사진이 감춰진 후, 후속 이벤트

Jquery 예제 - jquery yeje

> 2. '사진 보기'

Jquery 예제 - jquery yeje