안녕하세요. 글쓰는 개발자입니다.
오늘은 JQuery의 .one() 함수를 소개하고자 합니다.
저를 몇날 몇일간 괴롭혔던 검색제시어 영역 이외 클릭시 제시어 창 닫힘 및 입력값 초기화 기능 문제를 해결해준 고마운 기능입니다.
아래 내용에 대한 설명은 https://api.jquery.com/one/를 참고했습니다.
.one() | jQuery API Documentation
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type. The .one() method is identical to .on(), except that the handler for a given element and event type is unbound after its first invo
api.jquery.com
1. 사용배경
JQuery의 .on() 함수를 사용했으며, 이벤트가 지속적으로 발생하였음. 따라서, 이벤트 종료를 위해
-
event.preventDefault();
-
event.stopPropagation();
-
event.stopImmediatePropagation();
-
return false;
위의 4가지를 사용해봤지만 이벤트가 종료되지 않았음.
2. 해결방법
.one() 및 on()함수를 쓰되 .off(event)를 추가하는 두 가지 방식을 확인할 수 있었습니다. 저는 업무에서 .one()을 사용했지만 두가지 모두 소개하겠습니다. 버튼을 클릭하게되면 보통의 click 이벤트는 지속적으로 이벤트가 적용되지만 아래 예제의 경우 한 번만 적용됨을 확인하실 수 있습니다.
① .one() 함수 사용
<button type="button" id="oneClickTest">oneClick</button>
<script>
$( "#oneClickTest" ).one( "click", function( event ) {
alert( "This will be displayed only once." );
});
</script>
② .on() 함수 사용 및 $(this).off(event) 추가
<button type="button" id="onClickTest">onClick</button>
<script>
$( "#onClickTest" ).on( "click", function( event ) {
alert( "This will be displayed only once." );
$( this ).off( event );
});
</script>
3. 실제 업무 적용 예시
//영역 밖 클릭시 초기화[S]
$("body").one("click", function(e){
if((e.target).attr("class") != 'test'){
console.log("영역 밖");
}
});
scirpt단을 작업하시면서, 이벤트를 한 번만 사용해야 할 경우가 종종 있으실 텐데 유용하게 사용하시길 바라겠습니다.
'old > Javascript' 카테고리의 다른 글
[Javascript] 모바일 이미지 업로드시 이미지 회전 현상 해결 (3) | 2020.02.06 |
---|---|
[Javascript] var, let, const 차이(비교) (0) | 2020.02.03 |
[JavaScript] 회원가입, ID, 닉네임 유효성검사(Validation Check) (1) | 2020.01.22 |
[JQuery/ajax]비동기 검색제시어 기능/검색 API 활용 (4) | 2020.01.21 |
[Javascript] IE10, remove 함수 사용 불가 이슈 (0) | 2020.01.16 |