티스토리 뷰
jQuery란, 자바스크립트 라이브러리의 일종이다.
기능이 풍부하고. 여러 API들이 있어 이벤트 처리, Ajax 등을 간단하게 만들어준다.
jQuery의 장점 중 한가지로는 연쇄작용, 즉 ChainAction이 가능하다는 것이다.
예제를 통해 살펴보자.
"chain action"
예제 1
<p>의 innerText와 글자, 배경색을 각각 jQuery 미사용, 사용하여 변경해보자.
1. jQuery 로딩하기
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
2. jQuery 미사용 코드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Step01_ChainAction.jsp</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<p id ="one">p요소 입니다.</p>
<script>
/*
id가 one인 요소의
1. innerText를 안녕하세요
2. 글자색을 red
3. 배경색을 yellow
로 변경하기
*/
let p1 = document.querySelector("#one");
p1.innerText ="안녕하세요";
p1.style.color="red";
p1.style.backgroundColor = "yellow";
</script>
</body>
</html>
2. jQuery 사용 코드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Step01_ChainAction.jsp</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<p id ="two">p요소 입니다.</p>
<script>
/*
id가 two인 요소의
1. innerText를 안녕하세요
2. 글자색을 red
3. 배경색을 yellow
로 변경하기
*/
$("#two").text("안녕하세요").css("color","red").css("backgroundColor","yellow");
</script>
</body>
</html>
jQuery를 사용하면 한 줄이면 코딩이 끝남을 확인할 수 있다.
.을 찍어 계속해서 코드를 작성할 수 있는 것을 ChainAction이라 하는데, .text() 후 반환 된는 것이 p 요소이고, 글자색을 빨강으로 변경 후에 반환되는 것도 p요소 이므로 계속해서 .을 찍어 코드를 작성할 수 있는 것이다.
전체 코드
Step01_ChainAction.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Step01_ChainAction.jsp</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<p id ="one">p요소 입니다.</p>
<p id ="two">p요소 입니다.</p>
<script>
/*
id가 one인 요소의
1. innerText를 안녕하세요
2. 글자색을 red
3. 배경색을 yellow
로 변경하기
*/
let p1 = document.querySelector("#one");
p1.innerText ="안녕하세요";
p1.style.color="red";
p1.style.backgroundColor = "yellow";
/*
id가 two인 요소의
1. innerText를 안녕하세요
2. 글자색을 red
3. 배경색을 yellow
로 변경하기
*/
$("#two").text("안녕하세요").css("color","red").css("backgroundColor","yellow");
</script>
</body>
</html>
하지만, ChainAction이 모든 곳에 가능한 것은 아니다.
반환되는 값이 무엇인지 확인하고 그에 따라 ChainAction을 해야 한다.
다음 예제에서 살펴보자.
"모든 곳에 chain action을 사용할 수 있을까?"
예제 2
Step02_ChainAction2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Step01_ChainAction2.jsp</title>
<!-- jquery 로딩 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div>div1</div>
<div>div2</div>
<div id="one">div3</div>
<div>div4</div>
<div>div5</div>
<input type="text" id="two"/>
<input type="text" />
<script>
//chanin 형식으로 여러 동작을 한 줄의 javascript로 할 수 있다.
$("div").css("color","red").text("김구라");
//id가 one인 요소의 innerText를 읽어오는 동작이기 때문에 chain 형식의 동작은 불가능하다.
$("#one").text();
//id가 one인 요소에 innerText를 넣어주는 동작이므로 chain 형식으로 동작을 할 수 있다.
$("#one").text("해골");
//id가 two인 요소의 value 값을 읽어오는 동작이기 때문에 chain 형식의 동작은 불가능하다.
let b = $('#two').val();
//id가 two인 요소에 value 값을 넣어주는 동작이므로 chain 형식으로 동작을 할 수 있다.
$("two").val("안녕하세요");
</script>
</body>
</html>
.text()와 .val()은 각각 innerText와 value 값을 읽어오는 동작이므로 String으로 바뀌기 때문에 chain action이 불가능하다.
"EventListener"
이벤트 리스너 사용법
$( ).on("이벤트명",콜백함수);
[이벤트명]
click, mousedown, mousemove, mouseover, mouseout, focus, blur, keydown, keyup, keypressed, submit ...
예제 3
jQuery를 이용하여 box안에서 마우스를 움직일 때 해당 마우스의 좌표를 innerTexxt로 표시해보세요.
Step02_EventListner2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/jquery/Step02_EventListener2.jsp</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.box{
width:500px;
height:500px;
border: 1px solid red;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
$(".box").on("mousemove",function(e){
//e는 mouse event 객체이다.
console.log(e);
let x = e.offsetX;
let y = e.offsetY;
//이벤트가 일어난 바로 그 요소 선택 $(this)
$(this).text("x: "+x+" y: "+y);
});
</script>
</body>
</html>
예제 4
mousedown 이벤트가 일어난 div의
1. 배경색을 노란색
2. innerText를 "mousedown!"
으로 변경해 주세요.
Step02_EventListener3.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/jquery/Step02_EventListener3.jsp</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.box{
width:100px;
height:100px;
border: 1px solid red;
float: left;
}
</style>
</head>
<body>
<div class="box">box1</div>
<div class="box">box2</div>
<div class="box">box3</div>
<div class="box">box4</div>
<div class="box">box5</div>
<script>
/*
mousedown 이벤트가 일어난 div의
1. 배경색을 노란색
2. innerText를 "mousedown!"
으로 변경해 주세요.
*/
$(".box").on("mousedown",function(e){
$(this).css("background-color","yellow").text("mousedown!");
});
</script>
</body>
</html>
예제 5
input 요소에 keyup 이벤트가 일어나고 그 키가 만일 Enter라면
lit 요소를 동적으로 만들어서 innerText로 input 요소에 입력한 문자열을
읽어와서 넣어주고 li를 id가 msgList인 곳에 추가해 보세요.
Step02_EventListener4.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/jquery/Step02_EventListener4.jsp</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<p>메세지를 입력하고 Enter를 입력해보세요.</p>
<input id="inputMsg" type="text" placeholder="메세지 입력..."/>
<ul id="msgList">
<li>하나</li>
<li>두울</li>
</ul>
<script>
/*
input 요소에 keyup 이벤트가 일어나고 그 키가 만일 Enter라면
lit 요소를 동적으로 만들어서 innerText로 input 요소에 입력한 문자열을
읽어와서 넣어주고 li를 id가 msgList인 곳에 추가해 보세요.
*/
$("#inputMsg").on("keyup",function(e){
//만일 엔터를 쳤다면
if(e.keyCode==13){
//입력한 value 값을 읽어와서 li 요소를 만들어서 innerText를 출력하고 원하는 곳에 추가하기
$("<li>").text($("#inputMsg").val()).appendTo("#msgList");
//입력한 내용 지우기
$(this).val("");
}
});
</script>
</body>
</html>
$( ) 안의 속성에 <>가 들어가면, 새로 생성하겠다는 의미이다.
또한, appendTo()로 원하는 곳에 추가할 수 있다.
오늘은 jQuery의 chain action과 EventListener 사용법에 대해 알아보았다.
다음 게시물에서 마저 jQuery에 대해 알아보자.
'WEB > Java BackEnd' 카테고리의 다른 글
[WEB] jQuery #3 / fotorama 이미지 슬라이드 image slide (0) | 2021.12.01 |
---|---|
[WEB] jQuery #2 / Effect - 숨기기, 보이기, 토글, hide() (0) | 2021.12.01 |
[WEB-jsp/servlet] Filter 사용하기 / 한글 인코딩, 로그인에 필터 사용헤보기 (0) | 2021.11.30 |
[WEB-jsp/servlet] Forward와 Redirect의 비교 (0) | 2021.11.30 |
[WEB-jsp/servlet] Forward 예제 / RequestDispatcher (0) | 2021.11.30 |
- Total
- Today
- Yesterday
- html
- 문자열
- Oracle
- 자바
- jQuery
- append
- python
- brute force
- jsp
- 큐
- 백준
- 덱
- Case When
- 브루트 포스
- 스프링
- 고득점 키트
- web
- Java
- R
- 파이썬
- baekjoon
- 단계별로풀어보기
- bootstrap
- javascript
- Django
- 정렬
- CSS
- 자바스크립트
- 프로그래머스
- 장고
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |