KOSA full stack 교육(JQuery)
공식 문서의 문장이다.
jQuery는 빠르고, 가볍고, 다양한 기능이 포함된 JavaScript 라이브러리이다.
- HTML 문서 탐색 및 조작이 쉬움
- DOM 요소 선택, 변경, 삭제 등을 간단하게 처리할 수 있음
- 예: $('#id').hide();
- 이벤트 처리
- 클릭, 마우스 이동, 키보드 입력 등의 이벤트를 간단하게 처리 가능
- 예: $('button').click(() => {...});
- 애니메이션
- fadeIn, slideDown 등 시각적 효과를 손쉽게 구현
- Ajax 통신
- 서버와 비동기 데이터 교환을 간단한 코드로 수행
- 예: $.get('url', callback);
- 크로스 브라우징 호환성
- 다양한 브라우저에서 동일한 기능을 문제없이 구현할 수 있도록 도와줌
- 확장성과 유연성
- 수많은 플러그인과 사용자 정의 확장이 가능함
selector 예제1)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JQuery Selector...</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
//$ -> onload 방식이다
$(()=>{
//1. id값이 header인 태그의 직계자식인 span태그를 선택자로 지정
$('#header > span').css('color', 'crimson');
})
</script>
</head>
<body>
<h2 id="header">
<span>This is a heading</span>
</h2>
<p>This is a paragraph.</p>
<p class="content">This is another paragraph1.</p>
<p class="content theme">This is another paragraph2.</p>
<button>Click me to hide paragraphs</button>
<b>이 부분은 bold 하게 출력됩니다.</b>
</body>
</html>
$()로 css를 바꿀 수 있다.
이제 This is a heading 부분을 바꿔보자
$(()=>{
//1. id값이 header인 태그의 직계자식인 span태그를 선택자로 지정
$('#header > span').css('color', 'crimson').html("Jquery Selector Test");
})
이렇게 css를 바꿀 수 있다.
배경색도 바꿔보자
$(()=>{
//1. id값이 header인 태그의 직계자식인 span태그를 선택자로 지정
$('#header > span').css('color', 'crimson').html("Jquery Selector Test");
//h2 태그의 자식인 span을 선택자로 지정, 배경색을 gray로 ..
$('h2 span').css('background', 'gray');
})
p태그 문장을 바꿔보자
$(()=>{
//1. id값이 header인 태그의 직계자식인 span태그를 선택자로 지정
$('#header > span').css('color', 'crimson').html("Jquery Selector Test");
//h2 태그의 자식인 span을 선택자로 지정, 배경색을 gray로 ..
$('h2 span').css('background', 'gray');
//첫번째 p태그를 지정. 내용을 "첫번째 문장입니다"로 변경
$('p').html("첫번째 문장입니다");
})
이렇게되면 모든 p태그가 바뀌게 된다.
첫번째 p태그만 바꿔보자
$(()=>{
//1. id값이 header인 태그의 직계자식인 span태그를 선택자로 지정
$('#header > span').css('color', 'crimson').html("Jquery Selector Test");
//h2 태그의 자식인 span을 선택자로 지정, 배경색을 gray로 ..
$('h2 span').css('background', 'gray');
//첫번째 p태그를 지정. 내용을 "첫번째 문장입니다"로 변경
$('p:first').html("첫번째 문장입니다");
})
마지막은 p:last 이런식으로 접근한다. 상당히 직관적이다
혹은 다음과 같이 사용도 가능하다.
$('p').first().html("첫번째 문장입니다");
$('p').last().html("마지막 문장입니다");
//위의 방법은 두,세번째인 가운데를 선택하지 못함.
//이것을 극복하기 위해 나온 것이 p:eq(n)
$('p:eq(0)').html("첫번째 문장입니다");
$('p:eq(1)').html("두번째 문장입니다");
$('p:eq(2)').html("세번째 문장입니다");
버튼이 보이지 않도록 실습해보자
$('button').css('display','none');
p태그와 h2태그를 모두 선택자로 지정, 글자를 가운데 정렬 해보자
$('p, h2').css('text-align','center');
클래스 속성 값이 theme를 선택자로, 경계선을 지정해보자
$('.theme').css('border', '1px solid blue');
같은 코드로 다른 예제를 해보자
$(()=>{
//버튼을 클릭하면
$('button').click(()=>{
//p,h2태그 부분의 글자색이 blue로 바뀌고
$('p, h2').css('color', 'blue');
//첫번째 p태그의 내용은 첫번째 문장입니다로 변경되고
$('p:first').html('첫번째 문장입니다');
//버튼이 사라지도록
$('button').css('display','none');
});
})
여기서 이 코드를 보자
//첫번째 p태그의 내용은 첫번째 문장입니다로 변경되고
$('p:first').html('첫번째 문장입니다');
//$('p:first').text('첫번째 문장입니다');
//$('p:first').val('첫번째 문장입니다');
javascript -> jQuery
html() -> innerHTML
text() -> innerText
val() -> value
그러므로 위의 코드에서 .val은 적용이 안된다.
selector 예제2)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(()=>{
//input 태그 속성이름이 type 속성 값이 text인 애 선택
//$('input[type=text]').val("함동윤").css('color','blue');
$('[type=text]').val("쿠로미").css('color','blue');
//input 태그 속성 이름이 name 속성값이 한국/해당 폼안에 입력된 값을 받아서 alert 창으로 출력
let person = $('[name=한국]').val();
alert(person);
//input 태그 속성값 중에서 한국이라는 단어가 포함된 태그를 선택자로 지정하고 배경색을 yellow 로
$('input[name *= 한국]').css('background', 'yellow');
});
</script>
</head>
<body>
<h3> 폼 속성 선택자 사용법</h3>
<input type="text">
<input name="한국" value="한국사람">
<input name="한국인" value="KO한국인">
<input name="한국 민" value="한국 민">
<input name="대 한국 민" value="대 한국 민">
</body>
</html>
selector 예제3)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(()=>{
//1. body 태그의 모든 자식들을 선택자로 지정
$('body *').css('border','1px solid purple');
//2. body 태그의 직계 자식을 선택자로 지정
//$('body > *').css('border','1px solid purple');
})
</script>
</head>
<body>
<div>
<ul>
<li>Apple</li>
<li>Tomato</li>
<li>Banana</li>
<li>Peach</li>
<li>Graph</li>
</ul>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(()=>{
//1. body 태그의 모든 자식들을 선택자로 지정
//$('body *').css('border','1px solid purple');
//2. body 태그의 직계 자식을 선택자로 지정
$('body > *').css('border','1px solid purple');
})
</script>
</head>
<body>
<div>
<ul>
<li>Apple</li>
<li>Tomato</li>
<li>Banana</li>
<li>Peach</li>
<li>Graph</li>
</ul>
</div>
</body>
</html>
selector 예제4)
처음에 jsp 페이지와 html 페이지를 만들어놓고 시작한다
초기 세팅 코드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>결과페이지</h2>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
});
</script>
</head>
<body>
<form action="jq04_result.jsp" method="get">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
-> 다음과 같이 코드를 바꿔보았다.
<script>
$(function(){
//1. 입력 폼을 선택자로 지정.. 폼 안에 값을 James로 입력
name = 'James';
$('input[name=name]').val(name);
//2. result 영역에 입력된 고객 이름은 James입니다.가 출력되도록<h3>, color는 blue
$('#result').html('<h3><font color="blue">고객 이름은'+name+'</font></h3>');
});
</script>
그런데 이렇게 ' ' + name + ' ' 식으로 표현하는 것이 조금 번거롭다.
한번에 출력할 수 있는 보편적인 방법이
$('#result').html(`<h3><font color="blue">고객 이름은 ${name} </font></h3>`);
중간에 workshop 한문제
극장을 선택했을때, 해당 극장 이름을 alert하는 스크립트를 만들어보자!
$(function(){
$('select').change(function(){
let theater = $(this).val();
alert(theater);
})
});
workshop 문제
답안
<script>
$(function(){
$('#jojo').css('display','none');
$('#people').css('text-align','right');
$('#price').css('text-align','right');
$('#option').css('display','none');
//극장을 선택하면...선택한 극장값을 받아서 alert창으로 출력
$('select').change(function(){
var theater=$(this).val();
});
$('.time').click(function(){
var time = $(this).val();
//시간이 08:30 / 그 외시간...조건문
if(time=='08:30'){
$('#jojo').css('display','inline');
$('#ilban').css('display','none');
$('#cost').val(5000);
}else{
$('#jojo').css('display','none');
$('#ilban').css('display','inline');
$('#cost').val(9000);
}
});//
$('#people').change(function(){
var nump = $('#people').val();
var price = $('#cost').val();
$('#price').val(nump*price);
});
$('#op').click(function(){
if(this.checked){
$('#option').css('display','block');
}else{
$('#option').css('display','none');
}
});
});
</script>
JQuery Event 함수
event 예제 1) append
다음과 같은 html이 있다.
이렇게 만들어보자
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>append(), after() | prepend()</title>
<style>
body{
padding:50px;
}
div{
border:2px solid #bbb;
padding:10px;
margin:10px auto;
background-color: #eee;
}
span{
display:block;
width:65px;
font:bold 12px Arial;
color:white;
background:black;
padding:5px 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$('div')
.append('<span>1. Append </span>')
.after('<span>2. After</span>')
.prepend('<span>3. Prepend</span>')
.before('<span>4. Before</span>')
});
</script>
</head>
<body>
<div>
The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).
The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.
</div>
</body>
</html>
event 예제 2) append
button을 누르면 아래에 문장이 추가되도록 해보자
<script>
$(function(){
$('button').on('click',()=>{
let text1 = "<p>This is a Text...</p>";
//p태그에 위의 내용을 부착하기
$('p').append(text1);
});
});
</script>
아래는 버튼을 눌렀을 때 아래에 이어서 붙여지는 것을 구현한 것이다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>val()|text(),html()</title>
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$('button').on('click',()=>{
let text1 = "<p>This is a Text...</p>";
//p태그에 위의 내용을 부착하기
let text2 = $('p').html();
let text3 = document.createElement('p');
text3.innerHTML = 'This is a Text';
$('body').append(text1, text2, text3);
});
});
</script>
</head>
<body>
<p>This is a Text</p>
<button>Append text</button>
</body>
</html>
누를때마다 세 문장이 추가된다
event 예제 3) addClass
css를 jQuery에서 너무 직접 .css로 넣어주는 것은 안좋다.
분리시켜보자
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css() 사용남발로 JQuery와 css 분리가 제대로 안됨 :: addClass()</title>
<style>
.colorP{color: purple}
.colorT{color: tomato}
.colorG{color: green}
.borderG{ border:1px solid green}
.borderB{ border:1px solid blue}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$('button').on('click', ()=>{
$('#header > span').addClass('colorT');
$('p, h2').addClass('colorG');
$('p:last').addClass('borderB');
})
});
</script>
</head>
<body>
<h2 id="header">
<span>This is a heading</span>
</h2>
<p>This is a paragraph.</p>
<p class="content">This is another paragraph1.</p>
<p class="content theme">This is another paragraph2.</p>
<button>Click me to hide paragraphs</button>
</body>
</html>
event 예제 4) append_image
이미지가 3초에 한 번씩 맨 앞 이미지가 맨 뒤로 붙도록 한 코드이다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.star{border:2px solid black; width:200px; height:250px;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$('img').addClass('star');
//$('body').append($('img:eq(0)'));
//3초마다 첫 번째 애기들이 맨 뒤로 붙여지는 코드 ~
setInterval(()=>{
$('body').append($('img:eq(0)'));
},3000)
});
</script>
</head>
<body>
<img src='../image/kuromi1.jpeg'>
<img src='../image/kuromi2.jpeg'>
<img src='../image/romi1.png'>
<img src='../image/romi2.png'>
</body>
</html>
//$('img:eq(0)').append($('body')); <- 안됨!!
$('img:eq(0)').appendTo($('body'));
내용에 태그를 부착하려면 appendTo()
event 예제 5) bind
기본 html 코드이다. 여기에서부터 작업한다
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>bind::하나 이상의 이벤트를 묶는 기능 :: mouseenter, mouseleave</title>
<style>
.reverse{background:blue; color:white;}
.colorR{color:crimson;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
});//ready
</script>
</head>
<body>
<h2>As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on().</h2>
<h2>As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on().</h2>
<h2>As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on().</h2>
<button id="btn">버튼</button>
</body>
</html>
여기서 버튼을 누르면 색상이 바뀌도록 구현해보자.
<script>
$(function(){
$('#btn').on('click',()=>{
$('h2').addClass('colorR');
});
});//ready
</script>
여기의 on 자리에, bind를 적용해도 된다. 왜냐하면 묶는 기능이기 때문이다.
이제 글씨에 마우스를 가져다대면(hover) 배경 색을 바꿔보자
<script>
$(function(){
$('#btn').bind('click',()=>{
$('h2').addClass('colorR');
});
$('h2').bind({
mouseenter:function(){
$('h2').addClass('reverse');
},
mouseleave:function(){
}
})//bind
});//ready
</script>
하지만 이렇게하면 가져다 댄 h2영역만 바뀌는 것이 아닌 모든 h2영역이 바뀌게 된다. 그러므로 내가 선택한 h2만 색이 바뀌도록 해보자.
this를 사용하면 된다
$('h2').bind({
mouseenter:function(){
$(this).addClass('reverse');
},
mouseleave:function(){
}
})//bind
이제 마우스를 다시 밖으로 보내면 원래대로 돌려보내보자
<script>
$(function(){
$('#btn').bind('click',()=>{
$('h2').addClass('colorR');
});
$('h2').bind({
mouseenter:function(){
$(this).addClass('reverse');
},
mouseleave:function(){
$(this).removeClass('reverse');
}
})//bind
});//ready
</script>
이를 hover로도 구현할 수 있다.
<script>
$(function(){
$('h2').hover(function(){
$(this).addClass('reverse');
}, function() {
$(this).removeClass('reverse');
})
});//ready
</script>
이미지를 hover로 키웠다가 줄일 수 있다. 해보자!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.larger{ width:200px; border:2px solid tomato;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
//1. 마우스가 이미지 영역 안으로 들어가면 커지고 / 나오면 다시 원래대로
$('img').hover(function() {
$(this).addClass('larger');
}, function() {
$(this).removeClass('larger');
});
});
</script>
</head>
<body>
<h1>Bigger Image..</h1>
<img src="../image/kuromi1.jpeg" width="100">
<img src="../image/kuromi2.jpeg" width="100">
<img src="../image/romi1.png" width="100">
<img src="../image/romi2.png" width="100">
</body>
</html>