※ event
1. on() 메서드
- 이벤트를 부여하는 방식이 2가지로 나뉨 / 대괄호는 생략가능함
- .on(events[,selector][.data], handler)
- .on(events[, selector][, data])
* 이벤트를 부여하는 행위를 이벤트를 바인딩한다 라고 함
예제)
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<style>
.box {display: inline-block; width: 100px; height: 100px; background-color: orange; margin: 10px;}
</style>
<script>
$(function(){
$("button").on("click mouseenter", function(){
console.log($(this).text());
$(this).off("mouseenter");
// one은 이벤트를 딱 한번만 수행함
}).one("click", function(){
alert($(this).text());
});
// event delegation (이벤트 위임)
$(".wrap").on("click", ".box", function(){
let str = '<div class="box"></div>';
// document.body.innerHTML += str;
// $(".wrap")[0].innerHTML += str;
$(this).parent()[0].innerHTML += str;
})
});
</script>
</head>
<body>
<button>click me</button>
<div class="wrap">
<div class="box"></div>
</div>
</body>
</html>
예제2)
// event delegation (이벤트 위임)
let colorArr = ['red', 'orange', 'green']
let colorIdx = 0;
$(".wrap").on("click", ".box", function(){
let str = '<div class="box"></div>';
// document.body.innerHTML += str;
// $(".wrap")[0].innerHTML += str;
$(this).parent()[0].innerHTML += str;
// console.log(this).css("background-color");
// 1번방법
// $(".box").css("background-color", colorArr[colorIdx++ % 3]).css("border-color", colorArr[colorIdx % 3]);
// 2번방법 (Object 사용)
$(".box").css({
background:colorArr[colorIdx++ % 3],
borderColor:colorArr[colorIdx % 3]
});
※ effect
1. hide, show, toggle (드롭다운)
* 마우스리브, 마우스 엔터 (드롭다운시 사용)
- 제어되는 속성은 display
- $(selector),hide(speed, callback) / speed는 hide되는 속도, callback은 hide가 끝난뒤 할 일
2. fade
2-1) fadeTo() 메서드
- 완전히 사라지는게 아닌 특정 지정까지만 만드는것
2-2) fadeToggle() 메서드
3. slide
* 드롭다운 예제
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<style>
div:first-child {border: 2px solid; width: 800px; padding: 15px; margin: 0 auto;}
div:last-child {border: 2px solid; width: 800px; padding: 15px; margin: 0 auto; height: 300px; display: none;}
</style>
<script>
/*
show hide toggle
fadeIn fadeoOut fadeToggle
slideDown slideUp slideToggle, 슬라이드는 높이를 제어함, 드롭다운에서는 slide를 사용함
*/
$(function(){
$("div").eq(0).hover(function(){
$(this).next().stop().slideDown(100);
}, function(){
$(this).next().stop().slideUp(100);
})
})
</script>
</head>
<body>
<div>마우스 오버영역</div>
<div>토글영역</div>
</body>
</html>
4. animation
- css의 값을 바꾸는것과 비슷함
-
4-1) animate() 메서드
- $(selector).animate({params},speed,callback); / params는 key값을 지정해줘야함 {}는 필수값
- 여러속성을 조작할 수 있음
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
- 하이픈 사용시 '' 혹은 ""을 사용해야하며 하이픈을 사용안할시 camel표기법으로 작성해야함
* 예시) "margin-right" == marginRight
- 상대값 정의 가능
$("button").click(function(){
$("div").animate({
left: '250px',
height: '+=150px',
width: '+=150px'
});
});
- queue 사용 : animate() 호출을 차례로 작성하는 경우 메서드 호출로 내부 큐를 생성후 하나씩 차례대로 실행해줌
$("button").click(function(){
var div = $("div");
div.animate({height: '300px', opacity: '0.4'}, "slow");
div.animate({width: '300px', opacity: '0.8'}, "slow");
div.animate({height: '100px', opacity: '0.4'}, "slow");
div.animate({width: '100px', opacity: '0.8'}, "slow");
});
5. stop (거의 사용안함)
- 애니매이션이나 효과가 완료되기전에 중지하는데 사용됨
- 기본값은 false
6. callback
- 효과가 완료되고 나서 해야할 일
콜백예제)
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
콜백이 없는 예제)
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
7. chaining
- 다량의 처리를 한꺼번에 할 수 있다
- 브라우저가 동일한 요소를 두 번 이상 찾을 필요가 없음
- 셀렉터의 호출빈도를 낮춤
예제)
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
- 줄 바꿈 및 들여쓰기를 포함하여 원하는대로 형식을 지정할 수 있음
예제)
$("#p1").css("color", "red")
.slideUp(2000)
.slideDown(2000);
* builder 패턴
※ jQuery Get
- html요소와 속성을 변경하고 조작하기 위한 메서드가 있다.
1. DOM조작
2, Get content
- text() : 텍스트 내용을 설정하거나 반환
- html()
- val() : 값을 설정하거나 반환
3. Get Attributes
- attr()
2, 3 혼합예제)
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(function(){
$("div").eq(0).text("<b>굵은 글씨</b>")
$("div").eq(1).html("<b>굵은 글씨</b>")
// 함수를 통하여 제어
$("div").eq(2).html(function(idx, html){
console.log(html);
// 1번방법
// return html + "<p>추가글</p>"
// 2번방법 파라미터를 사용안함
return $(this).html() + "<p>추가글</p>";
//attr() 사용
}).attr({title:"추가된 제목", id:"div2"});
})
</script>
</head>
<body>
<div></div>
<div></div>
<div><p>기존 글</p></div>
</body>
</html>
※ Set
※ add Elements
1. 컨텐츠 추가
1-1) append
- 선택한 태그 끝에 추가
1-2) prepend()
- 선택한 태그 시작부분에 추가
1-3) after()
- 선택한 태그 뒤에 내용 추가
1-4) before()
- 선택한 태그 앞에 삽입
'Servlet, JSP > jQuery' 카테고리의 다른 글
23-03-02(1) jQuery (0) | 2023.03.02 |
---|