jQuery on() 메서드 예제 및 장점

巴扎黑
풀어 주다: 2017-06-25 10:37:43
원래의
1171명이 탐색했습니다.

jquery on() 메서드를 사용하여 events를 바인딩하는 것은 공식적으로 권장되는 방법입니다. 다음으로 편집기를 따라 jquery on() 메서드를 배워보세요. 친구들과 함께 배워보세요

jQuery on() 메서드는 이벤트 바인딩을 위해 공식적으로 권장되는 방법입니다.

$(selector).on(event,childSelector,data,function,map)
로그인 후 복사

이전에 확장된 몇 가지 일반적인 방법은 다음과 같습니다.

bind()

 $("p").bind("click",function(){
    alert("The paragraph was clicked.");
  });
  $("p").on("click",function(){
    alert("The paragraph was clicked.");
  });
로그인 후 복사

delegate()

$("#p1").on("click","p",function(){
    $(this).css("background-color","pink");
  });
  $("#p2").delegate("p","click",function(){
    $(this).css("background-color","pink");
  });
로그인 후 복사

live()

  $("#p1").on("click",function(){
    $(this).css("background-color","pink");
  });
  $("#p2").live("click",function(){
    $(this).css("background-color","pink");
  });
로그인 후 복사

위의 세 가지 방법은 jQuery1에 있습니다. 권장하지 않습니다. .8 이후에 사용하려면 1.9에서 live() 메서드 사용을 취소했기 때문에 on() 메서드 사용을 권장합니다.

팁: on()에 바인딩된 메서드를 제거해야 하는 경우 off() 메서드를 사용할 수 있습니다.

$(document).ready(function(){
  $("p").on("click",function(){
    $(this).css("background-color","pink");
  });
  $("button").click(function(){
    $("p").off("click");
  });
});
로그인 후 복사

팁: 이벤트에 하나의 작업만 필요한 경우 one() 메서드를 사용할 수 있습니다

$(document).ready(function(){
  $("p").one("click",function(){
    $(this).animate({fontSize:"+=6px"});
  });
});
로그인 후 복사

trigger() 바인딩

$(selector).trigger(event,eventObj,param1,param2,...)
$(document).ready(function(){
  $("input").select(function(){
    $("input").after(" Text marked!");
  });
  $("button").click(function(){
    $("input").trigger("select");
  });
});
로그인 후 복사

여러 이벤트가 동일한 함수에 바인딩됩니다

$(document).ready(function(){
 $("p").on("mouseover mouseout",function(){
  $("p").toggleClass("intro");
 });
});
로그인 후 복사

다양한 함수에 바인딩된 여러 이벤트

$(document).ready(function(){
 $("p").on({
  mouseover:function(){$("body").css("background-color","lightgray");}, 
  mouseout:function(){$("body").css("background-color","lightblue");}, 
  click:function(){$("body").css("background-color","yellow");} 
 });
});
로그인 후 복사

커스텀 이벤트 바인딩

$(document).ready(function(){
 $("p").on("myOwnEvent", function(event, showName){
  $(this).text(showName + "! What a beautiful name!").show();
 });
 $("button").click(function(){
  $("p").trigger("myOwnEvent",["Anja"]);
 });
});
로그인 후 복사

데이터를 함수에 전달

function handlerName(event) 
{
 alert(event.data.msg);
}
$(document).ready(function(){
 $("p").on("click", {msg: "You just clicked me!"}, handlerName)
});
로그인 후 복사

생성되지 않은 요소에 적용 가능

$(document).ready(function(){
 $("p").on("click","p",function(){
  $(this).slideToggle();
 });
 $("button").click(function(){
  $("<p>This is a new paragraph.</p>").insertAfter("button");
 });
});
로그인 후 복사

j쿼리 바인딩 이벤트에는 여러 가지 방법을 권장합니다. 바인딩을 위해 .on() 메서드를 사용하세요. 두 가지 이유가 있습니다:

1.on() 메서드는 페이지 요소에 동적으로 추가된 이벤트를 바인딩할 수 있습니다.

예를 들어 페이지 요소, 이벤트의 DOM에 동적으로 추가됩니다. .on() 메서드를 사용하여 바인딩하면 이벤트를 등록한 요소가 언제 추가되는지 신경 쓸 필요가 없으며 반복적으로 바인딩할 필요도 없습니다. 일부 학생들은 .bind(), .live() 또는 .delegate() 사용에 익숙할 수 있습니다. 소스 코드를 보면 실제로 .on() 메서드를 호출하고 .live()를 호출하는 것을 알 수 있습니다. 메소드는 jQuery1에 있습니다. 버전 9가 제거되었습니다.


bind:
function(
 types, data, fn ) {
  return this.on(
 types, null,
 data, fn );
},
live:
function(
 types, data, fn ) {
  jQuery(
this.context
 ).on( types, this.selector,
 data, fn );
  return this;
},
delegate:
function(
 selector, types, data, fn ) {
  return this.on(
 types, selector, data, fn );
}
로그인 후 복사

.on()에 바인딩된 이벤트를 제거하려면 .off() 메서드를 사용하세요.

2.on() 메서드 바인딩 이벤트는 효율성을 향상시킬 수 있습니다

이벤트 바인딩의 효율성을 높이기 위해 이벤트 버블링 및 프록시를 사용한다고 언급된 많은 기사가 있지만 대부분 구체적인 차이점을 나열하지 않았으므로 확인을 위해 다음을 수행합니다. 약간의 테스트를 해보겠습니다.

페이지에 5,000개의 li이 추가되었다고 가정하고 Chrome 개발자 도구 프로필을 사용하여 페이지 로딩 시간을 테스트합니다.

일반 바인딩(그렇게 부르자)


$(&#39;li&#39;).click(function(){
  console.log(this)
});
로그인 후 복사

바인딩 프로세스의 실행 시간

2013-08-13_190358

일반 바인딩은 5000li에 클릭 이벤트를 별도로 등록하는 것과 동일하며, 메모리 사용량은 약 4.2M, 바인딩 시간은 약 72ms입니다.

.on() 바인딩


$(document).on(&#39;click&#39;,
&#39;li&#39;,
function(){
  console.log(this)
})
로그인 후 복사

바인딩 프로세스의 실행 시간

2013-08-13_191010

.on() 바인딩은 이벤트 프록시를 활용하며 문서에는 하나만 등록됩니다. 클릭 이벤트는 약 2.2M의 메모리를 차지하며 바인딩 시간은 약 1ms입니다.

위 내용은 jQuery on() 메서드 예제 및 장점의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!