개발합니다
[jQuery] Event란? 본문
event란?
- 시스템에서 일어나는 사건을 의미한다. (클릭, 마우스 이동, 타이핑, 페이지 로딩 등 ..)
jQuery의 이벤트
- 크로스 브라우징의 문제를 해결해준다.
- click, ready와 같이 다양한 이벤트 헬퍼(helper)를 제공한다.
- bind로 이벤트 핸들러 설치, unbind로 제거 ==> on, off로 대체 됨.
- bind, unbind, trigger를 이용한 이벤트의 설치, 제거, 호출
function clickHandler(e){
alert('thank you');
}
$(document).ready(function(){
$('#click_me').bind('click', clickHandler); // click_me id를 가진 엘리먼트를 click할 시 clickHandler 호출 하는 이벤트 설치
$('#remove_event').bind('click', function(e){ // 한 번만 사용할 함수는 익명함수로 사용
$('#click_me').unbind('click', clickHandler); // click_me id를 가진 엘리먼트를 click할 시 clickHandler 호출 하는 이벤트 제거
});
$('#trigger_event').bind('click', function(e){
$('#click_me').trigger('click'); // click_me id를 가진 엘리먼트의 click 이벤트를 호출
});
})
- live, die
function clickHandler(e) {
alert('thank you');
}
$('#click_me').live('click', clickHandler);
$('#remove_event').live('click', function(e) {
$('#click_me').die('click', clickHandler); // live로 설치한 이벤트는 die로 제거할 수 있다.
});
$('#trigger_event').live('click', function(e) {
$('#click_me').trigger('click');
});
live를 이용해 존재하지 않는 엘리먼트에 대해서 미리 이벤트를 설치하고 위임해줄 수 있다.
- on, off를 통한 이벤트 등록, 삭제
$(function(){
$("#test").on({'mouseenter':function(){
$(this).css("background", "yellowgreen").text("마우스 올라감");
}, 'mouseleave':function(){
$(this).css("background", "yellow").text("마우스 내려감");
}, 'click':function(){
$(this).off('mouseenter').off('mouseleave').css("background", "orangered").text("기본값");
}});
});
1.7 버전부터 bind/unbind가 개선되어 나온 것이 on/off 이다.
on('이벤트명':function, '이벤트명':function, '이벤트명':function, '이벤트명':function, .....)과 같이 사용한다.
'Web > JavaScript' 카테고리의 다른 글
[jQuery] 폼이란? (Forms) (0) | 2022.03.28 |
---|---|
[jQuery] 엘리먼트 제어 (Manipulation) (0) | 2022.03.28 |
[jQuery] Chain이란? (0) | 2022.03.28 |
[jQuery] 선택자 (Selectors) (0) | 2022.03.28 |
[jQuery] jQuery란?, wrapper (0) | 2022.03.28 |