본문 바로가기

Ajax & jQuery

JQuery 셋팅 및 예제 (10.18필기보고보완)

1. JQuery 셋팅
2. (JQuery 예제) Javascript와 JQuery 비교 - test1. jsp , test2. jsp 

1. JQuery 셋팅

JQuery는 엘리먼트를 선택하여 효율적으로 제어할 수 있는 다양한 수단을 제공하는 자바스크립트 라이브러리

두가지로 나뉘어져 있음 - Script 파트와 GUI 파트 

 

1) Javascript 파트 다운받기

 

https://jquery.com/download/

 

Download jQuery | jQuery

link Downloading jQuery Compressed and uncompressed copies of jQuery files are available. The uncompressed file is best used during development or debugging; the compressed file saves bandwidth and improves performance in production. You can also download

jquery.com

Download the compressed, production jQuery Migrate 1.4.1 다운받기

 

compressed : 압축된것
uncompressed: 압축안된것

 

jquery-3.4.1.-min.js => 파일의 사이즈를 줄이기 위해서 공백을 다 없애 놓음
jquery-3.4.1.js => 체계적으로 편집이 되어있음

둘 중 어느거 받아도 상관 없음

 

다운받은 jquery-3.4.1.min.js (jQuery에서 javascript 파트를 담당) 파일을 eclipse에 넣어주기 

 

 

2) GUI 파트 다운받기 

맨 아래 참고!

 

 

 

2. JQuery 예제 - Javascript와 jQuery 비교

 

test1.jsp 

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	request.setCharacterEncoding("UTF-8");
	String cp = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JQuery 예제</title>
<script type="text/javascript" src="<%=cp%>/data/js/jquery-3.4.1.min.js"></script>

<script>

	// 1. Javascript
	//js에서는 변수 안에 함수를 넣을 수 있다
	//윈도우가 로딩될 때 자동으로 함수를 실행해라
	window.onload = function() {

		alert("JQUERY 환영합니다 !! ");

	}

	window.onload = function() {

		alert("JQUERY 진짜 환영합니다 !! ");

	}
	// 중첩되면 첫번째 alert는 보이지 않는다
	
	
	
	// 2. JQuery
	
	$(document).ready(function() {

		alert("환영!!");

	});

	$(document).ready(function() {

		alert("진짜 환영!!");

	});

	// (document).ready()를 쓰지 않고 줄여서 쓸 수도 있음
	$(function() {

		$(document.body).css("background", "pink");

	});

	//해당 문장을 body 부분에 나오게 해라
	$(function() {

		$("<div><p>제이쿼리</p></div>").appendTo("body");

	});
</script>

</head>
<body>
</body>
</html>

Javascript - 중첩되면 마지막 함수만 실행됨

jQuery - 순차적으로 모든 함수 다 실행됨

 

 

 

 

jQuery에서 $(document).ready()가 갖는 의미

$(document).ready(function() {
	// DOM이 로드되었을 때 실행되어야 하는 코드
});

이 구문 안에 위치한 코드는 DOM이 모두 준비된 이후에 실행된다

function Hello() {
	$("div.msg").addClass("letter");
}
$(document).ready(Hello);

이 $(document).ready() 함수는 다음과 같이 이미 정의해놓은 함수를 인자로 받을 수도 있다

(만일 Hello()함수가 다른데서 사용할 일이 없는 함수일 경우만)

$(document).ready(function() {
	$("div.msg").addClass("letter");
});

 

*비교*

js의 window객체의 onload 이벤트 핸들러에 함수를 지정하는 것

: 페이지를 구성하는 모든 리소스 (HTML,이미지 ..)를 불러온 시점에서 호출됨

 

$(document).ready() 함수

: 리소스가 아닌 DOM 객체가 생성되어 준비되는 시점에 호출됨 -> 페이지를 구성하고 있는 모든 이미지가 브라우저상에 렌더링될 때까지 기다릴 필요 없이 DOM이 준비되기만 하면 바로 실행됨

 

따라서 $(document).ready() 구문은 이 구문 안에 있는 코드가 실행되기 전에 페이지를 구성하는 DOM 객체를 먼저 로딩한다. DOM 객체를 다루는 코드를 사용한다면 반드시 이 구문 안에 해당 코드를 위치시켜야 제대로 작동이 가능하다.

 

 

test2.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	request.setCharacterEncoding("UTF-8");
	String cp = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=cp%>/data/js/jquery-3.4.1.min.js"></script>

<script type="text/javascript">
	
// jQuery 란걸 명시해줘야 실행이 됨
	$(function() { 

		// btnOK 를 클릭했을 때, 함수를 실행하라
		$("#btnOK").click(function() {
			
			// var msg = document.getElementById("userName").value; 와 동일 코드
			var msg = $("#userName").val();
			msg += "\r\n" + 
				$("input:radio[name=gender]:checked").val();
			//input box의 radio 버튼의 name=gender인 것의
			//checked 된 속성의 val 값을 가지고와라

			msg += "\r\n" +
				$("#hobby").val().join("|");

			alert(msg);

		});
	
	});

// 전형적인 Javascript
	function result() {

		var name = document.getElementById("userName").value;
		// document는 'body 안에 있는' 이라고 보면 됨
		// form을 안 쓰고 데이터를 가져올 수 있음 - form을 쓸 경우는 name을 이용하여 가져옴 

		alert(name);
	}
</script>


</head>
<body>

	이름:
	<input type="text" id="userName" />
	<br />
	 성별:
	<input type="radio" id="gender1" value="M" name="gender">남자
	<input type="radio" id="gender2" value="F" name="gender">여자
	<br />
	<!-- name의 gender는 같아야함 -->

	취미:
	<select id="hobby" multiple="multiple">
		<option value="여행">여행</option>
		<option value="영화">영화</option>
		<option value="운동">운동</option>
		<option value="게임">게임</option>
	</select>

	<br />
	<br />
	
	<!-- JQuery와 JavaScript 비교 -->
	 jQuery: <input type="button" value="확인" id="btnOK" /><br />
	 Javascript: <input type="button" value="확인" onclick="result();" /><br />


</body>
</html>

 

 

JQuery 버튼 실행 시 
Javascript 버튼 실행 시 

 

 

 

test3.jsp 

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8"); 
	String cp = request.getContextPath(); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<!-- 의존성 문제때매 이 css 위로 올려야함 -->
<style type="text/css">
	body{ font: 62.5% "굴림", sans-serif; margin: 50px;}
	ul#icons {margin: 0; padding: 0;}
	ul#icons li {margin: 2px; position: relative; padding: 4px 0; cursor: pointer; float: left;  list-style: none;}
	ul#icons span.ui-icon {float: left; margin: 0 4px;}
	#container { width: 300px;}
</style>

<!-- 인터넷에서 js와css를 찾아옴 -->
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<!-- JQuery는 ui 파트와 js 파트의 순서를 지켜줘야함(둘이 의존관계라서):
 ui를 나중에 link해주기 -->

<script type="text/javascript">

	$(function() {
		
		$("#dialog").hide(); //dialog 창을 숨겨라
		
		// 모달리스 :  창 띄워져도 뒤에 버튼이 눌려짐
		$("#btn1").click(function() {
			
			$("#dialog").dialog(); // dialog(사용자정의)를 dialog창으로 띄워라.
			
		});
		
		// 모달 : 창 띄워지면 뒤에 있는 걸 누를 수 없음
		$("#btn2").click(function() { 
			
			$("#dialog").dialog ({
				
				height:240,
				width:300,
				modal:true // 완료 전까지 이전창에 도달할 수 없음
					
			});
			
		});
		
		// 외부 jsp 띄우기
		 $("#btn3").click(function() { 	
			
			$("<div>").dialog ({
				
				modal:true,
				open:function() {
					
					$(this).load("ex.jsp"); // 자기 자신(this) 앞에다가 ex.jsp를 띄워라
					
				},
				
				height:400,
				width:400,
				title:"외부파일 창 띄우기"
					
			});
			
		});
		
	}); 

</script>
</head>
<body>

<div id="dialog" title="우편번호 검색">
	<p>동을 입력하세요</p>
	<p><input type="text"></p>
</div>

<div>
<input type="button" value="모달리스" id="btn1"/><br/>
<input type="button" value="모달" id="btn2"/><br/>
<input type="button" value="창 띄우기" id="btn3"/><br/>

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

활용 - 첨부파일 팝업에서 파일 선택 전까지 이전화면 클릭 못하게 할 때

모달리스 버튼 클릭 시  - 창이 떴어도 뒤에 다른 버튼들도 눌림

 

 

 

모달 버튼 클릭 시 - 이전 화면에 접근할 수 없어서 회색으로 뒷배경이 바뀜

 

 

test4.jsp - JQuery와 UI (JQuery-UI를 이용한 탭 만들기)

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
	String cp =request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<!-- 아래 3줄이 제이쿼리설정..? -->
<link rel="stylesheet"
href="<%=cp %>/data/css/jquery-ui.css" type="text/css">

<style type="text/css">
	body{ font: 62.5% "굴림", sans-serif; margin: 50px;}
	ul#icons {margin: 0; padding: 0;}
	ul#icons li {margin: 2px; position: relative; padding: 4px 0; cursor: pointer; float: left;  list-style: none;}
	ul#icons span.ui-icon {float: left; margin: 0 4px;}
	#container { width: 300px;}
</style>

<!-- jquery.com 에서 ui-tabs에서 소스 4줄 가져옴 : 통일성 -->
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<script type="text/javascript">

	$(function(){
	
		$("#container").tabs();
		
	});

</script>

</head>
<body>

<div id="container">

	<ul>
		<li><a href="#f1"><span>배수지</span></a></li> <!-- 첫번째라는 문자를 클릭하면 #f1으로 가게 -->
		<li><a href="#f2"><span>유인나</span></a></li>
		<li><a href="#f3"><span>안젤리나</span></a></li>
	</ul>
	
	<div id="f1"> <!-- 위 #과 같아야함 -->
		나는 배수지 입니다
	</div>
	
	<div id="f2"> 
		나는 유인나 입니다
	</div>
	
	<div id="f3"> 
		나는 안젤리나 입니다
	</div>

</div>

</body>
</html>

 

 

 

 

 

JQuery에서 제공하는 JQuery User Interface

https://jqueryui.com/ 

 

jQuery UI

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQue

jqueryui.com

1. jQuery UI 다운로드

1) stable 클릭 > 저장 

2) jquery-ui-1.12.1.zip 에 있는 jquery-ui.js 를  eclipse>WebContent>data>js폴더에 copy

3) css 세팅

jquery-ui-1.12.1.zip 에 있는 jquery-ui를 data>css에 copy

jquery-ui-1.12.1jqery-ui-1.12.1 > images - (jQuery에서 제공하는 아이콘들이 들어 있음) 를

eclipse>WebContent>data>css 아래 통째로 images폴더를 copy

 

 

 

 

2. 왼쪽 바에서 자신이 원하는 기능을 선택한다 

 

 

3. view source 를 클릭하면 아래 적용 예제 소스가 나오는데, 가져올 CDN 을 넣어준다. 

(서로 다른 프로젝트에서 같은 소스를 가져오고 싶을 때는 버전도 맞춰야하고 여러 문제가 있으므로 자신이 가지고 있는 local lib의 경로에서 가져오기보다, CDN방식으로 가져오는게 좋다)

 

 

test6.jsp

 

* alt: 사진을 못찾았을 때 띄우는 이미지

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
	String cp =request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<style>
  .carousel-inner > .item > img,
  .carousel-inner > .item > a > img {
      width: 70%;  //화면 사이즈 변경
      margin: auto;
  }
  </style>
</head>
<body>

<div class="container">
  <h2>Carousel Example</h2>
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
      <li data-target="#myCarousel" data-slide-to="3"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner">

      <div class="item active">
      <!-- alt: 사진을 못찾았을 때 띄우는 이미지 -->
        <img src="image/suzi.jpg" alt="suzi" width="460" height="345">
        <div class="carousel-caption">
          <h3>배수지</h3>
          <p>배수지는 가수예요</p>
        </div>
      </div>
	
		<!--  위에는 시작하자마자 뜨는 화면
		item은  -->
      <div class="item">
        <img src="image/hyoju.jpg" alt="hyoju" width="460" height="345">
        <div class="carousel-caption">
          <h3>한효주</h3>
          <p>Thank you, 한효주!</p>
        </div>
      </div>
    
      <div class="item">
         <img src="image/sulhyun.jpg" alt="sulhyun" width="460" height="345">
        <div class="carousel-caption">
          <h3>New York</h3>
          <p>We love the Big Apple!</p>
        </div>
      </div>
      
       <div class="item">
         <img src="image/nakyung.jpg" alt="nakyung" width="460" height="345">
         </div>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>

</body>
</html>