GitHub

https://github.com/Backcoder-June

BackCoder 기록 그리고 숙달

Back to the JavaScript

[jquery] EventListener => on/off

Backcoder 2022. 8. 3. 19:47

[ 이벤트 처리  EventListener 방식  => jquery 버전 ]

: on / off

function f1 ( ) {  ~  } 

 

<리스너 버전>
 document.querySelector("input").addEventListener("click", f1 ,false);

<jquery 버전>
$("input:button").on("click", f1 );

: 버튼input 태그를 클릭하면 f1 함수 실행 하겠다.  

 

( $("input:button").click(f1); 

이 문법도 된다. 이렇게도 된다. 편의에 따라 사용. )

 

< 같은 태그 같은 이벤트에 여러 함수 적용 가능 >  = Listener 하고 같음 

 

$("h1#first").on("click", f1);
$("h1#first").on("click", f2);

: 클릭하면 f1 함수 f2 함수 둘다 실행된다. 

 

 

< 걸어둔 이벤트 함수 제거 가능 >  = Listener 하고 같음 


< removeEventListener  >

- 함수 선택안해두면 모든 함수 제거
$("input:button").off("click");
//$("input:button").off("click", f1 ); 

- 함수 선택하면 선택한 함수만 제거 


$("input:button").on("click", function(){
    $("h1#first").off("click", f1); });

: input 버튼클릭하면 => h1태그에 걸린 클릭이벤트를 off 시키겠다. 

 

 

 

[ preventDefault 기본 내장이벤트 제거 ]

: 이벤트객체 사용하는거나, preventDefault 키워드 똑같이 사용한다. 

 

$("a").on("click", function(e){
e.preventDefault();
});

 

< 사용자 편의성 > 

조건만족 못해서 다시 입력하게 하고자 할때, 

- 입력내용 초기화 

- focus( )  

주는걸 기본으로 해두자. 

if(find1 == true){
 alert(message);
 e.preventDefault();
 $("input:text:first").val("");
 $("input:text:first").focus();
 }

< boolean 전역변수 >

message 띄우는거 반복문로직 쪽에서 하면 매번 반복될 수 있으니, 

boolean 전역변수 설정해두고

그거 이용해서 나중에 최종적으로 적용되게 하는 방식 사용하자  

 

 

 

 

-------

 

[ 하나 태그에 => 여러 종류 이벤트 가능 ] 

 

1. 하나하나 주기 
$("div#box").on("click", function(){
$(this).css("background-color", "green");
});

$("div#box").on("mouseenter", function(){
$(this).css("background-color", "yellow");
});

$("div#box").on("mouseleave", function(){
$(this).css("background-color", "blue");
});

 

=> box라는아이디를가진div태그에 click이벤트발생하면  green색으로 

=> box라는아이디를가진div태그에 mouseenter이벤트발생하면  yellow색으로 
=> box라는아이디를가진div태그에 mouseleave이벤트발생하면  blue색으로 

: 복수개의 복합적인 이벤트가 잘 적용 된다. 

 

 

 

2. 객체형태로 한방에 주기 
$("div#box").on(
{
click : function(){$(this).css("background-color", "green");},
mouseenter : function(){$(this).css("background-color", "pink");},
mouseleave : function(){$(this).css("background-color", "black");}
}
);