jQuery 연결 이벤트 on에 대해 알아보자.
jQuery 연결 이벤트 on에 대해 알아보자.
REDINFO
몇달 전 2023-07-23 03:51:27

jQuery 에서 사용되는 on 이벤트는 연결 이벤트중 하나로 click, mousedown,keydown 등의 여러 동작 이벤트를 연결하여 처리가 가능하다. 참고로 같은 용도로 사용되는 연결 이벤트 bind, delegate, live 등이 있지만 jQuery API 문서내 권고 사항으로 본다면 on 이벤트로 대체해야 추후 높은 버전을 사용하더라도 변경없이 사용이 가능하다. on 이벤트 파라미터는 jQuery 공식 문서상 아래와 같이 명시되어 있다. 

events
    Type: String
    One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
selector
    Type: String
    A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
data
    Type: Anything
    Data to be passed to the handler in event.data when an event is triggered.
handler
    Type: Function( Event eventObject [, Anything extraParameter ] [, ... ] )
    A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.

 

| 참고 사이트 

 
.on() | jQuery API Documentation
.on() | jQuery API Documentation
api.jquery.com/on/

 

on 이벤트 연결 

가장 먼저 살펴볼 소스는 on 이벤트를 연결하는 방법이다.

<!-- jquery 라이브러리 로드 -->
<script src="//code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>

<button class="click">클릭</button>
<button class="mouseover">마우스오버</button>

<script type="text/javascript">
	$('.click').on('click',function(){
		alert('click 이벤트');
	});
	$('.mouseover').on('mouseover',function(){
		alert('mouseover 이벤트');
	});	
</script>

 

on 연결을 끊는 off 이벤트

이번에는 off 이벤트를 이용하여 연결된 이벤트를 종료하는 예제에 대해 알아보자

<!-- jquery 라이브러리 로드 -->
<script src="//code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>

<h1>이벤트 제어</h1>
<button class="on">클릭 이벤트 실행</button>
<button class="off">클릭 이벤트 종료</button>

<h1>이벤트 상태</h1>
<input type="text" class="update" value="종료" />

<h1>이벤트 실행</h1>
<button class="click">클릭</button>

<script type="text/javascript">
	//상태값
	var click = false;

	// 이벤트 제어
	$('.on').on('click',function(){ on(); });
	$('.off').on('click',function(){ off(); });

	function on(){
		if( click === true){ alert('이벤트가 실행중입니다.'); return false; }
		click = true;
		update();
		$('.click').on('click',function(){
			alert('click 이벤트');
		});
	}

	function off(){
		if( click === false){ alert('이벤트가 실행중이지 않습니다.'); return false; }
		click = false;
		update();
		$('.click').off('click');
	}

	function update(){
		if( click === true){ $('.update').val('실행'); }
		else{ $('.update').val('종료'); }
	}

	
</script>

 

| 결과

 

이벤트 제어 란은 클릭 이벤트를 발생시키거나 종료 시키는 구간이고 이벤트 상태는 제어에 의해 현재 상태를 표기하는 부분이다. 처음에는 이벤트가 없으므로 클릭 이벤트 실행을 통해 이벤트를 연결해 주어야한다.

 

on 이벤트의 전역 제어

on, off 와 같은 이벤트들은 Document 가 로드된다음 현재 상태의 dom 요소 기준으로 연결을 하기 때문에 중간에 요소가 추가될 경우 해당 요소에는 이벤트가 발생되지 않는 문제가 있다. 이러한 부분은 주로 ajax 를 통해 특정 구간에 요소를 추가했을 시 발생될 수 있는데 이때는 매번 on 이벤트를 다시 실행해줘야 하는 불편함이 있다. 이를 해결 할 수 있는 방법은 연결 시 선택자가 기준이 아닌 docuement 기준으로 연결을 하는것이다. 해당 예제는 아래와 같다. 

<!-- jquery 라이브러리 로드 -->
<script src="//code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>

<h1>이벤트 제어</h1>
<button class="add">클릭 이벤트 추가</button>

<h1>이벤트 실행</h1>
<button class="click">클릭</button>

<script type="text/javascript">

$('.add').on('click',function(){
	$('body').append('<button class="click">클릭</button>\n');
});

$(document).on('click','.click',function(){
	alert('click 이벤트');
});
</script>

 

| 결과

 

클릭 이벤트를 추가하면 이벤트 실행 아래로 클릭 버튼이 계속해서 생성된다. 이때 어떤것을 클릭하더라도 이벤트를 그대로 연결이 된다. 예제 소스를 보면 알겠지만 이벤트 연결 선택자를 document 로 했을 시에는 인자값이 첫번째는 연결 이벤트 타입, 두번째는 선택자, 세번째는 핸들러인것을 알 수 있다. 만약 이벤트를 기본형태 요소의 선택자로 했을 경우에는 추가된 클릭 버튼에는 이벤트가 연결이 안되기 때문에 실행이 되지 않는다. 이때는 할 수 없이 아래의 예제 소스처럼 계속해서 이벤트를 끊고 연결해 줘야한다.

<!-- jquery 라이브러리 로드 -->
<script src="//code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>

<h1>이벤트 제어</h1>
<button class="add">클릭 이벤트 추가</button>

<h1>이벤트 실행</h1>
<button class="click">클릭</button>

<script type="text/javascript">

$('.add').on('click',function(){
	$('body').append('<button class="click">클릭</button>\n');
	$('.click').off('click').on('click',function(){ alert('click 이벤트'); });	
});

$('.click').on('click',function(){
	alert('click 이벤트');
});
</script>

 

마지막으로 on 이벤트는 아래 예제 소스와 같이 타입 뒤로 특정 객체변수를 전달할 수 있는데 그렇게 많이 사용되는 방법은 아니니 참고만 하도록 하자

<!-- jquery 라이브러리 로드 -->
<script src="//code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>

<h1>이벤트 실행</h1>
<button class="click" data-msg="click 이벤트">클릭</button>

<script type="text/javascript">

var data = $('.click').data();
$('.click').on('click',data,function(e){
	alert(e.data.msg);
});
</script>

 

클릭 버튼 실행 시 data-msg 에 저장된 `click 이벤트`를 받아서 알럿창을 띄울 수 있다. 받을 시에는 이벤트 핸들러 변수내 데이터로 접근하면된다. 

이 포스트글이 도움이 되었나요?
4
카테고리 연관글

Comment

댓글작성

0(500) | 1(30)