제이쿼리 한번만 실행 - jeikwoli hanbeonman silhaeng

목차

  1. one() 예제 - 이벤트가 1개인 경우
  2. one() 정의
  3. one() 구문
  4. one() 예제 - 이벤트가 2개인 경우

※ 각 요소에 대해 1회 클릭때만 글자 커짐. 2회 때부터는 작동 X.

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

    $("p").one("click", function(){

        $(this).animate({fontSize: "+=6px"});

    });

});

</script>

<p>홈짱닷컴 Homzzang.com</p>

<p>홈페이지 제작관리 강의</p>

결과보기

one() 정의

선택 요소에 대해 하나 이상의 이벤트 핸들러를 첨부 후, 이벤트 발생 시 실행할 함수 지정. (이 경우, 이벤트 핸들러 함수는 각 요소에 대해서 오직 한번만 실행. ) 

one() 구문

$(selector).one(event,data,function)

[매개변수]

event

필수. 선택 요소에 부착할 하나 이상의 이벤트. 

이벤트는 공백으로 분리해 나열하며, 각 이벤트는 유효해야 함.

data

선택. 함수에 전달할 추가적인 데이터.

function

필수. 이벤트 발생 시 실행할 함수.

one() 예제 - 이벤트가 2개인 경우

※ 각 요소에 (1회 클릭, 1회 더블클릭) 때만 글자 커짐. 2회 때부터는 작동 X

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

    $("p").one("click dblclick", function(){

        $(this).animate({fontSize: "+=6px"});

    });

});

</script>

<p>홈짱닷컴 Homzzang.com</p>

<p>홈페이지 제작관리 강의</p>

결과보기

최초 1회만 이벤트를 실행하고 이후 이벤트 동작을 하지 않습니다.

.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

위에 설명했던 .one() 함수로 동작하는 버튼입니다.

다음은 .on() / .off() 함수로 동작하는 버튼입니다.

안녕하세요. 글쓰는 개발자입니다.

오늘은 JQuery의 .one() 함수를 소개하고자 합니다.

저를 몇날 몇일간 괴롭혔던 검색제시어 영역 이외 클릭시 제시어 창 닫힘 및 입력값 초기화 기능 문제를 해결해준 고마운 기능입니다.

아래 내용에 대한 설명은 //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() 함수를 사용했으며, 이벤트가 지속적으로 발생하였음. 따라서, 이벤트 종료를 위해

  1. event.preventDefault();

  2. event.stopPropagation();

  3. event.stopImmediatePropagation();

  4. 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단을 작업하시면서, 이벤트를 한 번만 사용해야 할 경우가 종종 있으실 텐데 유용하게 사용하시길 바라겠습니다.

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

[ JQUERY ] 한번만 실행하기 -  One

예제설명 : 입력 창을 최초에 클릭하면 기본 value값을 초기화 하는 이벤트

          $(document).ready(function(){
   $('#contents').one("click", function(){
      $('#contents').attr("value","");
   });
});

Contents 객체를 클릭하면 최초 한번만 클릭 이벤트가 실행되어 contents value값을 초기화 한다.

Toplist

최신 우편물

태그