반응형
이벤트 연결 메소드1
아래와 같은 식으로 변화했으며,
현재는 on과 off를 사용한다.
이벤트 연결 | 이벤트 제거 |
$(selector).bind(…) | $(selector).unbind(…) |
↓ | ↓ |
$(selector).live(…) | $(selector).die(…) |
↓ | ↓ |
$(selector).delegate(…) | $(selector).undelegate(…) |
↓ | ↓ |
$(selector).on(…) | $(selector).off(…) |
on, one, off 사용법
$(selector).on(event, childSelector, data, function)
// 선택된 요소와 하위 요소에 한 개 이상의 이벤트를 바인딩
// 현재 로드 된 요소 및 스크립트로 생성될 새로운 요소에도 적용됨
$(selector).one(event, data, function)
// 선택된 요소와 하위 요소에 한 개 이상의 이벤트를 바인딩. 이벤트가 한번만 수행되고 제거됨
$(selector).off(event, selector, function(eventObj))
// 선택된 요소에 on메소드로 연결된 이벤트를 제거
- 정적 요소 생성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.sttBg {
background-color: black;
color: white;
}
.dynmBg {
background-color: hotpink;
color: lime;
}
.fontGold {
color: gold;
}
</style>
</head>
<body>
<p>on(event[, selector][, data], fn) / one(event[,data], fn) / off(event[, selector][, fn]</p>
<div></div>
<script src="../js/jquery-3.7.1.min.js"></script>
<script>
// data {key:value} 형식으로 작성 후 ebent객체의 data속성으로 key에 접근하여 값을 얻음
// 정적요소 대상 on()
$('p').on('mouseover', {static:'정적요소bind방식'},function(e){
$(this).toggleClass('sttBg');
// console.log(e.data.static);
$(this).text(e.data.static);
});
</script>
</body>
</html>
- 동적 요소 생성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.sttBg {
background-color: black;
color: white;
}
.dynmBg {
background-color: hotpink;
color: lime;
}
.fontGold {
color: gold;
}
</style>
</head>
<body>
<div></div>
<script src="../js/jquery-3.7.1.min.js"></script>
<script>
// 동적 요소 생성
let addP = $('<p>동적요소1</p><p>동적요소2</p>');
$('div').append(addP);
// 동적요소 대상 부모요소.on(event[,childSelector][,data],fn)
// delegate방식 >> 정적요소 부모에게 이벤트를 주고 자식은 위임받는 형태
// $(부모).on(이벤트, 이벤트의 적용대상인 자식요소, 함수);
$('div').on('mouseover', 'p', {dynamic:'동적요소delegate방식'},function(e){
$(this).toggleClass('dynmBg');
$(this).text(e.data.dynamic);
});
</script>
</body>
</html>
- off : 이벤트 제거
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.sttBg {
background-color: black;
color: white;
}
.dynmBg {
background-color: hotpink;
color: lime;
}
.fontGold {
color: gold;
}
</style>
</head>
<body>
<p>on(event[, selector][, data], fn) / one(event[,data], fn) / off(event[, selector][, fn]</p>
<div></div>
<button>일괄 제거(정적대상으로만)</button>
<button>동적요소</button>
<button>특정 이벤트 제거</button>
<script src="../js/jquery-3.7.1.min.js"></script>
<script>
// 정적요소 대상 on(event[,data],fn)
$('p').on('mouseover', {static:'정적요소bind방식'},function(e){
$(this).toggleClass('sttBg');
$(this).text(e.data.static);
});
// 정적대상 이벤트2
let rmv;
$('p').on('mouseover', rmv = function(){
$(this).toggleClass('fontGold');
});
// 동적 요소 생성
let addP = $('<p>동적요소1</p><p id="pp">동적요소2</p>');
$('div').append(addP);
$('div').on('mouseover', 'p', {dynamic:'동적요소delegate방식'},function(e){
$(this).toggleClass('dynmBg');
$(this).text(e.data.dynamic);
});
$('div').on('mouseover', '#pp', function(){
alert('접근시 알람');
});
$('button').eq(0).on('click', function(){ // 바인딩 - 정적요소 대상
// 동적인 방식으로 만들어진 것은 제거되지 않음
$('p').off('mouseover'); // p요소에 부여된 마우스 오버 이벤트 제거
$('p').text('배경색 토글 이벤트가 제거되었음');
});
$('button').eq(1).on('click', function(){
// 동적대상 이벤트 제거는 - 부모의 이벤트를 제거해야 함
$('div').off('mouseover'); // 동적대상의 부모에게 부여된 이벤트를 제거
});
$('button').eq(2).on('click', function(){
// 같은 이벤트 중 일부분의 처리만 제거
$('p').off('mouseover', rmv);
$('div').off('mouseover', '#pp');
});
</script>
</body>
</html>
이벤트 연결 메소드 (bind) : 정적 대상 방식
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
bind
실행(로딩)전 document에 생성되어 있는 요소에만 이벤트 핸들러가 동작
(*동적 요소에는 이벤트 핸들러(처리기)가 동작하지 않음) <br><br>
<div class="wrapper">
<input type="button" class="btn" value="정적버튼">
<input type="button" id="clear" value="해제">
<!-- 동적버튼이 위치할 지정 -->
</div>
<script src="../js/jquery-3.7.1.min.js"></script>
<script>
// 정적 대상 방식
let bb = $('<input type="button" class="btn" value="bird 버튼">');
$('.wrapper').append(bb);
// bind(event, fn)
$('.btn').on('click', function(){ // 정적대상 방식
$('<input>',{
type: 'button',
class: 'btn',
value: '새 버튼'
}).appendTo('.wrapper');
});
$('#clear').click(function(){
$('.btn').off('click');
});
</script>
</body>
</html>
=> 동적 버튼 확인
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
bind
실행(로딩)전 document에 생성되어 있는 요소에만 이벤트 핸들러가 동작
(*동적 요소에는 이벤트 핸들러(처리기)가 동작하지 않음) <br><br>
<div class="wrapper">
<input type="button" class="btn" value="정적버튼">
<input type="button" id="clear" value="해제">
<!-- 동적버튼이 위치할 지정 -->
</div>
<script src="../js/jquery-3.7.1.min.js"></script>
<script>
// 정적 대상 방식
let bb = $('<input type="button" class="btn" value="bird 버튼">');
$('.wrapper').append(bb);
for(let i=0; i<3; i++) {
let nb = $('<input type="button" class="btn" value="동적for버튼' + i + '">');
$('.wrapper').append(nb);
if(i == 1) {
// bind(event, fn)
$('.btn').on('click', function(){ // 정적대상 방식
$('<input>',{
type: 'button',
class: 'btn',
value: '새 버튼'
}).appendTo('.wrapper');
});
}
}
$('#clear').click(function(){
$('.btn').off('click');
});
</script>
</body>
</html>
=> 동적for버튼0과 1의 경우 on인 것을 기준으로 미리 실행되기에 정적 버튼으로 취급한다.
이벤트 연결 메소드 (delegate) : 동적 대상 방식
1. 동적 버튼 추가 및 해제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
delegate(위임, 대리)
부모의 이벤트를 물려받은 선택자에 적용되는 이벤트
(* 부모요소는 반드시 정적대상이어야 함/ 부모를 특정하기 힘들 경우 최상단 document지정 가능)
<div class="wrapper">
<input type="button" class="btn" value="정적버튼">
<input type="button" id="clear" value="해제">
<!-- 동적버튼이 위치할 지정 -->
</div>
<script src="../js/jquery-3.7.1.min.js"></script>
<script>
// delegate(selector, event, fn) 에서 on 메소드로 변경됨
// on(event, selector, fn)
$('.wrapper').on('click', '.btn', function(){ // 동적대상 방식
$('<input>',{
type: 'button',
class: 'btn',
value: '새 버튼'
}).appendTo('.wrapper');
});
$('#clear').on('click', function(){
// 이벤트 부여대상의 이벤트 해제
$('.wrapper').off('click');
});
</script>
</body>
</html>
2. 파일 선택 영역 추가
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<input type="file">
<button id="add">파일 선택 영역 추가</button>
</div>
<script src="../js/jquery-3.7.1.min.js"></script>
<script>
$('#add').click(function(){
// 동적으로 생성됨
let v_file = "<p>";
v_file += "<input type='file'>";
v_file += "<button class='del'>삭제</button>";
v_file += "</p>";
$('div').append(v_file);
});
// delegate방식으로 삭제버튼에 이벤트 주기
// $(부모).on(event, selector, fn);
$('div').on('click', '.del', function(){
// class=del의 부모는 p이지만 동적요소이므로 부모자격이 없음
// empty(대상요소만 지워줌와 remove(대상 요소와 자식까지 지워줌) 사용 가능
console.log(this); // <button class='del'>삭제</button>"
console.log( $(this).parent() ); // 부모 p 요소 포함하여 출력됨
$(this).parent().remove();
});
</script>
</body>
</html>
반응형
'jQuery' 카테고리의 다른 글
[jQuery] 15장 DOM 탐색 (0) | 2024.02.26 |
---|---|
[jQuery] 14장 trigger와 trigger Handler (0) | 2024.02.26 |
[jQuery] 12장 이벤트 (0) | 2024.02.23 |
[jQuery] 11장 스타일시트 관련 메소드, 넓이와 높이 관련 메소드 (0) | 2024.02.23 |
[jQuery] 10장 요소 추가 메소드, 삭제 및 복사 메소드 (0) | 2024.02.22 |