달밤에 코딩

jQuery 이벤트 등록, 삭제 본문

Front-End/jQuery

jQuery 이벤트 등록, 삭제

bamDal 2022. 6. 3. 17:25
반응형

jquery

 

 

jQuery 에서는 이벤트를 등록하고 실행할 수 있다.

jQuery에서 사용되는 이벤트는 종류가 굉장히 많다. 
많이 사용되는 몇가지

jQuery 이벤트 종류

이 외에 다른 이벤트를 알고싶다면
API 사이트 에서 events 카테고리를 참고하면 된다.

 

 

' 이벤트 등록 '

이벤트 등록 방법
1. $(selector).추가할이벤트(실행할함수)
2. 
$(selector).on("추가할 이벤트",실행할 함수)

 

1. $(selector).click(function(){});

  • .click() : 추가할 이벤트
  • function(){} : 이벤트가 실행되면 실행할 함수

 

//hover = mouseenter + mouseleave
		$("#overzone").hover(
			function(){
				$(this).css({"background-color":"red"});
			},
			function(){
				$(this).css({"background-color":"green"});
			}
		);

=> id가 overzone 인 요소에 마우스를 오버하면 이 요소(this) 에 css 를 적용한다.

 

 

2. $(selector).on("click",function(){});

  • on으로 생성한 이벤트는 off를 통해 키고 끌 수 있다.
  • "click" : 추가할 이벤트
  • function(){} : 이벤트가 실행되면 실행할 함수

 

$("p").on("dblclick",function(e){
    $(this).css({'color':'blue'});
});

p태그인 요소를 더블클릭하면 이 요소(this)에 css가 적용된다.

 

1)  p태그인 요소가 여러개이다보니 클릭한 요소만 바뀌도록 하기 위해선 2가지 방법이 있다.

$("p").on("click",function(e){
			console.log(e);
			//$('p').css({'color':'orange'}); // 클릭한 요소만 바뀌어야 한다. -> 2가지 방법
			//1. e.target 이용 **
			//$(e.target).css({'color':'orange'});
			//2. this를 이용 *
			$(this).css({'color':'orange'});

		});

$('p').css({'color':'orange'}); 를 사용하면 모든 p태그가 orange 색으로 바뀐다.

1. e.target 이용
$(e.target).css({'color':'orange'}); 

2. this 이용
$(this).css({'color':'orange'});

 

2)  on을 이용해서 여러 이벤트 등록하기

$("#mousezone").on({
    mouseenter:function(e){
        $(this).html('마우스가 들어간 상태');
    },
    mouseleave:function(e){
        $(this).html('마우스가 나간 상태');
    },
    mousedown:function(e){
        $(this).html('마우스가 눌린 상태');
    },
    mouseup:function(e){
        $(this).html('마우스버튼 뗀 상태');
    }
});

mouseenter : function(){}
이벤트종류 : 실행할 함수

 

' 이벤트 삭제 '

on으로 생성된 이벤트는 off로 제거할 수 있다.

- on으로 이벤트 등록

//$(selector).on("추가할 이벤트",실행할 함수)
$("#btn").on("click",function(){ // 익명함수 or 콜백함수라고 부른다.
    $("body").append("<button class='newBtn' onclick='clickEvt()'>click</button>");
    $("body").append("<button class='newBtn2'>click2</button>");
});

 

- off로 이벤트 삭제

// 이벤트 삭제(on으로 생성된 이벤트는 off로 제거할 수 있다.)
$('#evtDel').on('click',function(){
    $('#btn').off('click');
});

위에 아이디가 btn 인 요소('버튼 생성' 버튼)에 클릭이벤트를 등록해놨는데 
아이디가 evtDel인 요소('이벤트 삭제' 버튼) 을 클릭하면 '버튼 생성' 버튼에 등록해놨던 이벤트를 off로 삭제한다.

'버튼 생성'  버튼에는 버튼을 누르면 click, click2 버튼이 생성되는 이벤트가 등록되어 있는데
'이벤트 삭제' 버튼을 누르면 이 이벤트가 제거되어 
생성 버튼을 눌러도 더이상 버튼이 생성되지 않는다.

 

 

 

반응형

'Front-End > jQuery' 카테고리의 다른 글

jQuery : focus(), blur() 이벤트  (0) 2022.06.06
jQuery 나중에 생성된 요소에 이벤트 등록  (0) 2022.06.06
jQuery 기초 빠르게 훑기  (0) 2022.06.02
Comments