Notice
Recent Posts
Recent Comments
Links
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Today
In Total
관리 메뉴

A Joyful AI Research Journey🌳😊

[19] 230125 Ch. 12 jQUERY, Ajax, JSON: 1. jQuery, 2. 첫 번째 jQuery 프로그램, 3. jQuery 문장의 구조, 4. jQuery를 이용한 이벤트 처리 · 5. 애니메이션 효과 [K-디지털 트레이닝 19일] 본문

🌳Bootcamp Revision✨/JavaScript, jQuery, Ajax, JSON

[19] 230125 Ch. 12 jQUERY, Ajax, JSON: 1. jQuery, 2. 첫 번째 jQuery 프로그램, 3. jQuery 문장의 구조, 4. jQuery를 이용한 이벤트 처리 · 5. 애니메이션 효과 [K-디지털 트레이닝 19일]

yjyuwisely 2023. 1. 25. 12:50

230125 Wed 19th class

Ch. 12 jQUERY, Ajax, JSON
진도: p. 452 ~ (교재: HTML5 + CSS3 + JavaScript로 배우는 웹프로그래밍 기초, 저자: 천인국)

 

HTML5+CSS3+JavaScript로 배우는 웹프로그래밍 기초 | 천인국 - 교보문고

HTML5+CSS3+JavaScript로 배우는 웹프로그래밍 기초 | 웹프로그래밍 초보자도 쉽게 배우는 웹 개발 지침서!이 책은 웹프로그래밍을 처음 배우는 초보자들을 위해 기초부터 차근차근 설명한다. 1~3장에

product.kyobobook.co.kr


오늘 배운 것 중 기억할 것을 정리했다.


지난 수업 때 배운 것 중 다시 기억할 것

display: none; is commonly used with JavaScript to hide and show elements without deleting and recreating them. The <script> element uses display: none; as default. 

2023.01.05 - [1. Revision 2023/CSS3] - *[7] 230105 Ch. 6 CSS 레이아웃과 애니메이션(1): 레이아웃의 기초, 요소 위치 정하기, (요소) · 의미적 요소를 이용한 레이아웃, 효과, CSS3 변환 · 3차원 변환 · 애니메이션

 

참고 p. 196 

display:block /*블록(block)*/
display:inline /*인라인(inline)*/
display:none /*없는 것으로 간주됨*/
display:hidden /*화면에서 감춰짐*/

display: none: 문서의 흐름에서 해당 요소를 완전히 배제하고자 할 때 사용된다.
display: hidden: 문서의 흐름에서 요소가 제거되지 않지만 보이지는 않는 상태이다.
참고하기: https://www.w3schools.com/css/css_display_visibility.asp


Ch. 12 jQUERY, Ajax, JSON

책의 목차
-jQuery
-첫 번째 jQuery 프로그램
-jQuery 문장의 구조
-jQuery를 이용한 이벤트 처리
-jQuery를 이용한 애니메이션 효과
-jQuery를 이용한 DOM 변경
-jQuery를 이용한 CSS 조작
-Ajax 개요
-jQuery를 이용하여 Ajax 사용하기
-JSON

1. jQuery p. 452

일종의 자바 스크립트 라이브러리
jQuery를 사용하면 자바 스크립트 프로그래밍 양을 상당히 줄일 수 있다.
배우기 쉽다.
무료이다. 설치 과정도 필요 없이 그냥 한 줄만 소스에 추가하면 된다.

자바스크립트 jQuery
id가 myPara인 요소를 찾아서 내용을 변경한다.
document.getElementsById("myPara").innerHTML = "안녕하세요?" $("#myPara").html("안녕하세요?")

 

1.1 jQuery 사용 방법

둘 중 하나를 선택한다.

1) jQuery에서 jQuery 파일을 다운하는 방법
http://www.jquery.com에서 다운로드
크롬의 경우 다른 이름으로 저장으로 다운받는다. 

다운로드 버전에도 2가지가 존재하는데 compressed(압축) 버전과 uncompressed 버전이 있다.
compressed 버전은 공백이 모두 제거된 버전이며 uncompressed 버전은 공백이 유지되어 있는 버전이다.
따라서 uncompressed 버전의 용량이 약 3배 정도 커서 속도에는 불리하나 개발/디버깅 작업 시에는 유용하게 사용할 수 있다.

다운 받아서 js 파일에 복사해서 붙여넣는다.

아래처럼 사용한다. 

<script type="text/javascript" src="js/jquery-3.6.3.js"></script>

 

2) 실행시마다 구글이나 마이크로소프트에서 jQuery 파일을 포함하는 방법
- 공개 서버로부터 네트워크를 통하여 웹페이지를 실행할 때마다 다운로드받을 수도 있다. 
- 1.10.1버전

<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js"></script>

 

2. 첫 번째 jQuery 프로그램

https://jquery.com/download/의 Downloading jQuery using Bower의 두번째 코드를 사용한다.

<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js></script>
</head>

3. jQuery 문장의 구조 p. 2567

jQuery 문장의 의미는 HTML 요소를 선택하여 (또는 찾아서), 선택된 요소에 어떤 동작(action)을 시키는 것이다.

$(selector).action();

$: jQuery라는 의미이다.
selector: 선택자 (CSS선택자와 똑같다. id(#), 클래스(.) 등)

2023.01.03 - [1. Revision 2023/CSS3] - [5] 230103 Ch4 CSS3 스타일 시트 기초

$(selector).: 선택자에 의하여 선택된 요소
action(): 선택된 요소의 함수 호출

ex) $("h1")은 페이지에 있는 모든 <h1>요소를 찾아서 갖다 달라는 의미이다.


3.1 선택자

1) 타입 선택자

요소의 이름을 적어서 요소를 선택한다. 

<body>
<p> 이것은 문단입니다. </p>
<p> 이것은 문단입니다. </p>
</body>

예를 들어 <p>라고 하면 페이지 안의 모든 <p> 요소가 선택된다. 

$("p").hide();

 

모든 <p> 요소를 찾아서 화면에 표시한다.

$("p").show()

 

2) .class 선택자

요소를 정의할 때 요소에 클래스 이름을 줄 수 있다. 

<body>
<h1> 제목 </h1>
<p class="menu">1. 구입 </p>
<p> 2. 결제 </p>
</body>

.class와 같은 형식으로 특정한 클래스에 이름을 가지는 요소를 선택할 수 있다.

$(".menu").slideup();

 

class=group1인 요소를 슬라이드업 방식으로 표시한다.

$(".group1").slideup()

 

3) #id 선택자

요소를 정의할 때 요소에 id 속성을 부여할 수 있다.

<body>
<h1> 제목 <h1>
<p> 문단입니다. </p>
<p id="check"> 문단입니다. </p>
</body>

#id와 같은 형식으로 특정한 아이디를 갖는 요소를 선택할 수 있다.

$("#check").show();



id=id9
인 요소를 화면에서 감춘다.

$("#id9").hide()

 

4) 그 외의 선택자

형식                                   설명
$("*") 모든 요소를 선택한다.
$(this) 사용자가 선택한, 현재 요소를 선택한다.
$("p.myClass")  <p> 요소 중에서 class="myClass"인 요소
$("p:first") 첫번째 <p> 요소 
$("p:last") 마지막 <p> 요소 
$("div span") <div> 안에 포함된 <span> 요소
$(":button") 버튼과 버튼 타입 요소를 모두 선택,
<button></button> 혹은 <input type="button"/>이 모두 선택된다.

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.


3.2 일반적인 jQuery 구조 p. 459

아래 구조를 사용하는 이유는 문서가 완전히 로드되기 전에 jQuery 코드가 실행하는 것을 방지하기 위해서이다. 만약 문서가 완전히 로드되지 않은 상태에서 jQuery 메서드가 실행되면 오류가 발생한다. 

$(document).ready( function(){
// DOM이 로딩되어서 준비가 되면 작업을 시작한다.
// 구체적으로 jQuery 메서드들을 호출한다.
});

$(document): DOM을 의미한다. HTML 문서 전체를 선택한다. 
ready: '준비가 되면'이라는 event이다.
function(){;: 함수 정의

기본적인 구조이다.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BASIC</title>
<style>
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
$(document).ready(function(){
});
</script>
</head>
<body>
</body>
</html>

 

DOM을 읽은 후 함수를 실행한다는 의미이다. 

아래처럼 jQuery를 먼저 선언한 후 <script>을 사용한다.

<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<script>
//$(document): html문서 전체를 선택한다.
$(document).ready(function (){
});
</script>
</body>
</html>

4. jQuery를 이용한 이벤트 처리 p.460

jQuery를 사용하면 이벤트 처리를 쉽게 할 수 있다.
예를 들어 다음과 같은 것이 이벤트이다.

- 요소를 마우스로 클릭한다. → click 이벤트 발생
- 키보드의 키를 누른다. → keypress 이벤트 발생
- 사용자가 입력필드에 값을 입력한다. → change 이벤트 발생

이벤트의 예제)

<html>
<head>
<script>
function add(){
}
</script>
</head>
<body>
<input type="button" value="확인" onclick="add()">
</body>
</html>

 

4.1 이벤트의 종류

아래는 중요한 이벤트들이다.

키보드  마우스
  • keypress
  • keydown
  • keyup
  • click
  • dblclick
  • mouseenter
  • mouseleave
  • submit
  • change
  • focus
  • blur
  • resize
  • load
  • unload
  • scroll

 

4.2 jQuery 이벤트 메서드의 구문

 

예제) 버튼을 클릭하면 빨간 상자가 나온다.

display: none; is commonly used with JavaScript to hide and show elements without deleting and recreating them. The <script> element uses display: none; as default. 

<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
$(document).ready(function(){
// "눌러보세요"라는 버튼을 클릭하면
//$("#button1").on("click", function(){ // 기본적인 이벤트 핸들링
$("#button1").click(function(){ // 위 기본적인 이벤트 핸들링 변형.
// alert("연결됨.");
$("#box").show(); //show: <div>를 보여준다.
})
});
</script>
<style>
#box{ background-color: red; width: 100px; height: 100px; display: none;}
</style>
</head>
<body>
<input type="button" id="button1" value="눌러보세요." onclick="click()">
<div id=box></div>
</body>

결과)

4.3 이벤트 등록 방법

정식 방법: 원래 이렇게 해야 된다. 동적으로 추가된 요소에서는 정식 방법을 사용한다. 

$("#div1").on('click', function()
{
...
});

단축 메서드 방법: 99%의 개발자는 이렇게 사용한다. 이미 DOM 트리 안에 요소가 생성되어 있을 때만 가능하다. 

$("#div1").click( function(){
...
});

 

4.4 마우스 이벤트 p. 462

mouseenter: 요소 안으로 마우스가 진입한다.
mouseleave: 마우스가 요소를 빠져나간다.
mousedown: 왼쪽 마우스 버튼이 눌려지면 발생한다.
mouseup: 왼쪽 마우스 버튼이 떼어지면 발생한다.
mouseover: 마우스가 특정 요소 위에 있으면 발생한다.

예제) <div> 태그로 사각형을 만들고 마우스 커서가 사각형 안을 넘어오면 변수의 값을 증가시켜 화면에 출력하는 프로그램

<head>
<meta charset="UTF-8">
<title>mouse</title>
<!-- 사각형의 스타일 정의 -->
<style>div.out{width:200px;height:60px;background-color:yellow;}</style>
<!-- jQuery 라이브러리 참조 -->
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<div class = "out">
<p> 마우스를 여기로 움직이세요. </p>
<p> 0 </p>
</div>
<script>
var i = 0;
//class명이 out인 div에 마우스를 올렸을 때(mouseover) 이벤트 적용
//(=out 클래스의 <div>에서 mouseover 이벤트가 발생하면)
$("div.out").mouseover(function(){
//document.getElementsTagName("p")[0].innerHTML="mouse over"; 자바스트립트
//첫 번째 <p>요소의 내용을 "mouse over"로 변경한다.
$("p:first").text("mouse over");
//마지막 <p>요소에 증가변 변수 i의 값을 출력한다.
$("p:last").text(++i);
})
</script>
</body>

결과)

 

4.5 focusblur 이벤트 p. 464

focus (커서가 깜빡거림) 이벤트는 입력 필드가 키보드 포커스를 얻으면 발생한다. 
반대로 입력 필드가 키보드 포커스를 잃으면 blur (커서 잃음)이벤트가 발생한다.
ex) blur 이벤트: NAVER 회원가입의 경우, blur 이벤트가 발생할 때 아이디 밑에 빨간색 폰트로 '필수 정보입니다'가 뜬다. 

예제)  입력 필드를 만들고 포커스를 얻으면 입력 필드의 배경색을 노란색으로 변경해보고 포커스를 잃으면 흰색으로 변경해 보자.
this: 위의 input을 따라간다. 위의 것을 이어서 적용한다.

<head>
<meta charset="UTF-8">
<title>focus and blur p.464</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
$(document).ready(function(){
//input태그의 커서(포커스)를 얻으면 input태그의 배경색을 노란색으로 변경한다.
$("input").focus(function(){
//css: jQuery에서 css를 적용할 때 쓰는 함수
//this: 위의 input을 따라간다. 위의 것을 이어서 적용한다.
$(this).css("background-color","yellow");
})
//input태그의 커서(포커스)를 잃으면 input태그의 배경색을 흰색으로 변경한다.
$("input").blur(function(){
$(this).css("background-color","white");
})
})
</script>
</head>
<body>
아이디: <input type = "text" name = "name">
</body>

결과)

 

4.6 이벤트 처리기 함수 안에서 사용 가능한 정보 p. 465

모든 이벤트 처리 함수는 이벤트 객체를 전달받는다. 이벤트 객체는 많은 속성과 메서드를 가지고 있는데 그 중에서 유용한 것은 다음과 같다.

- pageX, pageY: 이벤트가 발생했을 당시의 마우스 위치
- type: 이벤트의 종류(ex. "click")
- which: 눌려진 마우스 버튼이나 키

예제) 

<style>
body{background-color:#eef;}
div{padding:20px;}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
</script>
</head>
<body>
<div id="log"></div>
<script>
$(document).mousemove(function(e){
$("#log").text("e.pageX: "+e.pageX+"e.pageY: "+e.pageY);
})
</script>
</body>

결과)


5. jQuery를 이용한 애니메이션 효과 p. 466

5.1 show()hide()

$(selector).show( duration, complete );

selector: 선택자
show: 요소를 표시한다.
duration: "slow", "fast", 또는 밀리초 단위로 지정할 수 있다.
complete: 콜백함수로서 show() 메서드가 완료된 후에 호출되는 메서드를 지정한다.
ex) 알림창을 띄운다.
In computer programming, a callback or callback function is any reference to executable code that is passed as an argument to another piece of code; that code is expected to call back (execute) the callback function as part of its job.

프로그래밍에서 콜백(callback) 또는 콜백 함수(callback function)는 다른 코드의 인수로서 넘겨주는 실행 가능한 코드를 말한다. 콜백을 넘겨받는 코드는 이 콜백을 필요에 따라 즉시 실행할 수도 있고, 아니면 나중에 실행할 수도 있다.

예제) 버튼을 누르면 이미지가 서서히 화면에 표시된다. 화면에서 감춘다.

<style>
/*display:none; 처음에는 이미지를 화면에서 감춘다. */
img{width:120px;height:100px;display:none;}
</style>
<script src="https://code.jquery.com/jquery-3.6.3.min.js">
</script>
<script>
$(document).ready(function(){
//show 버튼을 클릭하면
$("#show").click(function (){
//$(선택자).show(duration, complete)
//slow: 버튼이 클릭되면 이미지가 느리게 나타난다.
$("#coffee").show("slow",function(){alert("이미지가 나타난 후에 알림창을 띄우세요.")})});
//hide 버튼을 클릭하면
$("#hide").click(function (){
$("#coffee").hide("slow",function(){alert("이미지가 사라진 후에 알림창을 띄우세요.")})});
});
</script>
</head>
<body>
<button id="show"> Show it </button>
<button id="hide"> Hide it </button>
<img id="coffee" src="image/coffee.jpg" alt="">
</body>

결과) show()는 왼쪽 상단에서 시작해서 커지고, hide()는 왼쪽 상단쪽으로 사라진다. 

 


5.2 toggle() p. 467

요소가 감추어져 있으면 표시하고, 표시되어 있으면 감춘다.
show(), hide()처럼 왼쪽 상단이 기준이다. 

What is toggle CS?
A toggle, in general computing, is a switch between one setting and another. The term implies that it is a switch that has only two outcomes: A or B, or on or off. It is found in almost every aspect of computing when there is an options or preferences list.


예제) 이미지가 나타났다 사라지기를 반복한다.

$("#toggle").click(function (){
$("#coffee").toggle("slow",function(){alert("하나의 버튼으로 나타나고 사라진다.")})});
<button id="toggle"> Toggle it </button>

 

결과)


5.3 animate()

animate(): 어디로나 이동이 가능하고 어떤 효과도 가능하다.

$(selector).animate( properties, duration, easing, complete )

selector: 선택자
animate: 요소를 애니메이트하다.
properties: 애니메이트될 CSS 속성, 목표값을 여기에 적는다. CSS 형식으로 원하는 속성을 넣으면 된다. 
duration: speed는 "slow", "fast", 또는 밀리초 단위로 지정할 수 있다.

Easing functions specify the rate of change of a parameter over time.

easing (default: swing) Type: String
A string indicating which easing function to use for the transition.
 
예제) <div> 요소를 왼쪽에서 100px 떨어진 위치로 이동한다. 이미지를 왼쪽에서 오른쪽으로 옮긴다.
투명도와 크기도 변경된다.

<style>
#hong{width:120px;height:100px;position:relative;}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#hong").animate({
left: "100px",
opacity: "0.5",
width:"150px"})
})
});
</script>
</head>
<body>
<img src = "image/coffee.jpg" id="hong"><br>
<button> animate() </button>
</body>
결과)


5.4 stop()

stop(): 모든 애니메이션을 중간에 중단한다. 

ex) id=stop인 버튼이 클릭되었을 때, 애니메이션을 중지한다.

$("#stop").click(function () {
$("#dog").stop();
});

예제)

<style>
#hong{width:120px;height:100px;position:relative;}
</style>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#hong").animate({
left: "1000px",
opacity: "0.5",
width:"150px"})
});//# animate 끝
$("#stop").click(function(){
$("#hong").stop();
});
});
</script>
</head>
<body>
<img src = "image/coffee.jpg" id="hong"><br>
<button> animate() </button><button id="stop"> stop() </button>
</body>

예제 2) 출처: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_stop_slide

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
font-size: 18px;
text-align: center;
background-color: #555;
color: white;
border: solid 1px #666;
border-radius: 3px;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
<button id="stop">Stop sliding</button>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
</body>
</html>

결과)




5.5 fadeIn()/ fadeOut() 

The fadeIn() method gradually changes the opacity, for selected elements, from hidden to visible (fading effect).
The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden (fading effect).
Note: Hidden elements will not be displayed at all (no longer affects the layout of the page).

 

5.6 slideUp(), slideDown()

SlideUp(): 요소를 밀어올린다.
SlideDown(): 요소를 밀어내린다.

<style>
/*display:none; 처음에는 이미지를 화면에서 감춘다. */
img{width:120px;height:100px;display:none;}
</style>
<script src="https://code.jquery.com/jquery-3.6.3.min.js">
</script>
<script>
$(document).ready(function(){
//show 버튼을 클릭하면
$("#show").click(function (){
//$(선택자).show(duration, complete)
//slow: 버튼이 클릭되면 이미지가 느리게 나타난다.
$("#coffee").show("slow",function(){alert("이미지가 나타난 후에 알림창을 띄우세요.")})});
//hide 버튼을 클릭하면
$("#hide").click(function (){
$("#coffee").hide("slow",function(){alert("이미지가 사라진 후에 알림창을 띄우세요.")})});
//toggle 버튼을 클릭하면
$("#toggle").click(function (){
$("#coffee").toggle("slow",function(){alert("하나의 버튼으로 나타나고 사라진다.")})});
//fadeIn 버튼을 클릭하면
$("#fadeIn").click(function (){
$("#coffee").fadeIn("slow",function(){alert("fadeIn은 영화처럼 등장한다.")})});
//fadeOut 버튼을 클릭하면
$("#fadeOut").click(function (){
$("#coffee").fadeOut("slow",function(){alert("fadeOut은 영화처럼 사라진다.")})});
//slideDown 버튼을 클릭하면
$("#slideDown").click(function (){
$("#coffee").slideDown("slow",function(){alert("slideDown은 요소를 밀어내린다.")})});
//slideUp 버튼을 클릭하면
$("#slideUp").click(function (){
$("#coffee").slideUp("slow",function(){alert("slideUp은 요소를 밀어올린다.")})});
});
</script>
</head>
<body>
<button id="show"> Show it </button>
<button id="hide"> Hide it </button>
<button id="toggle"> Toggle it </button>
<button id="fadeIn"> Fade it in </button>
<button id="fadeOut"> Fade it out </button>
<button id="slideDown"> Slide it down </button>
<button id="slideUp"> Slide it up </button>
<img id="coffee" src="image/coffee.jpg" alt="">
</body>

결과) 

 


5.7 메서드 체이닝 (method chaining) p. 472

메서드 체이닝(method chaining): 동일한 요소에 대한 여러 개의 메서드를 하나로 연결해서 실행할 수 있다. 
동일한 요소에 대한 여러 개의 jQuery 메서드를 하나의 문장으로 실행할 수 있다. 

예제) "#dog" 요소에 대한 show(), fadeOut(), slideDown() 메서드를 연결해서 호출한다.
"#dog" 요소는 화면에 나타나고 이어서 페이드아웃, 슬라이드다운된다.

<style>
#coffee{width:120px;height:100px;display:none;}
</style>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#coffee").show().fadeOut("slow").slideDown("slow");
})
});
</script>
</head>
<body>
<button>메서드 체이닝 시작</button><br>
<img src="image/coffee.jpg" id="coffee">
</body>

결과)


 

728x90
반응형
Comments