CDN Content Delicery Network
: 파일을 여러 서버에 분산시키고 사용자가 접속한 지역과 가장 가까운 곳에서 파일을 전송하는 기술(트래픽 분산)
jQuery 라이브러리
: 모든 웹 브라우저에서 동작하는 클라이언트용 자바스크립트 라이브러리
Tip) querySelector()와 달리 여러 개 선택, querySelectorAll()과 달리 반복문 사용 X
$(document).ready(function (){ //window.onload 이벤트와 같은 기능 수행
//$(선택자).메서드(매개변수, 매개변수)
});
//Expose jQuery to the global object
window.jQuery.window.$ = jQuery;
사용 목적
- 쉬운 객체 모델과 관련된 처리 구현
- 쉽고 일관된 이벤트 연결 구현
- 쉬운 시각적 효과 구현
- 쉬운 Ajax 응용 프로그램 개발
문서 조작
1. 객체 조작
객체 조작 메서드 | 설명 | 예시 |
attr() | 매개변수가 있으면 get 없으면 set |
var src = $('img').attr('src'); //img 태그의 src 속성 추출 |
//속성 값을 입력해 속성 지정
$('img').attr('src', 'http://placehold.it/300x200');
//객체를 입력해 속성 지정
$('img').attr({
src: 'http://placehold.it/300x200',
width: 300,
height: 200
});
//함수를 입력해 속성 지정
$('img').attr('src', function(index) ({
var size = (index + 1) * 100;
//url 리턴
return 'http://placehold.it/' + size + 'x100';
});
Tip) Method Chaining: jQuery에서 문서 객체를 조작하는 메서드는 호출 이후에 자신을 다시 반환하기 때문에 메서드를 연속해서 사용할 수 있다
2. 텍스트 조작
글자 조작 메서드 | 설명 |
html() | 태그 조작 |
text() | 글자 조작 |
$(document).ready(function() {
$('h1:nth-child(1)').text('<a href="#">text()</a>')
$('h1:nth-child(2)').html('<a href="#">text()</a>')
});
3. 클래스 조작
Tip) 클래스를 추가, 제거할 때 attr() 메서드를 사용한다면 문자열 연산을 사용해 번거롭다
클래스 조작 메서드 | 설명 |
addClass() | 클래스 추가 |
removeClass() | 클래스 제거 |
toggleClass() | 클래스 전환 |
<style type="text/css">
#box {
width: 100px;
height: 100px;
background-color: red;
}
#box.hover {
background-color: grey;
border-radius: 50px;
}
</style>
<script>
$(document).ready(function() {
$('#box').hover(function() { //마우스 올릴 때
$('#box').addClass('hover');
}, function() {
$('#box').removeClass('hover');
});
});
</script>
<body>
<div id="box"></div>
</body>
이벤트
1. 이벤트 연결
간단한 이벤트 연결 메서드 | 설명 |
hover | mouseenter - mouseleave 동시 연결하는 복합 메서드 |
blur | |
focus | |
focusin | |
focusout | |
load | |
resize | |
scroll | |
unload | |
click | |
dbclick | |
mousedown | |
mouseup | |
mousemove | |
mouseover | |
mouseout | |
mouseenter | |
mouseleave | |
change | |
select | |
submit | |
keydown | |
keypress | |
keyup | |
error | |
ready |
$(selector).연결메서드(function (이벤트) { });
$('h1').click(function () { });
//hover의 첫 번째 매개변수에는 mouseenter 이벤트 리스너, 두 번째는 mouseleave 이벤트 리스너 입력
$(document).ready(function(){
$('h1').hover(function() {
$(this).css({
color: 'red'
});
}, function() {
$(this).css({
color: ''
});
});
});
2. 이벤트 사용
: 사용자 정의 이벤트, 새로 나온 이벤트 등은 간단한 이벤트 연결 메서드를 사용할 수 없고, on() 로 연결해야 한다
이벤트 연결 메서드 | 설명 |
on() | 이벤트 연결 |
off() | 이벤트 제거 |
// 방법1
$(selector).on(eventName, eventHandler);
// 방법2
$(selector).on({
eventName_0: eventHandler_0,
eventName_1: eventHandler_1,
eventName_2: eventHandler_2
});
3. 기본 이벤트 제거
P391