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

WBOY
풀어 주다: 2016-05-16 15:42:07
원래의
1076명이 탐색했습니다.

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

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

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

바인드()

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

대리자()

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

라이브()

  $("#div1").on("click",function(){
    $(this).css("background-color","pink");
  });
  $("#div2").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(){
 $("div").on("click","p",function(){
  $(this).slideToggle();
 });
 $("button").click(function(){
  $("<p>This is a new paragraph.</p>").insertAfter("button");
 });
});
로그인 후 복사

jQuery에서 이벤트를 바인딩하는 방법에는 여러 가지가 있습니다. 두 가지 이유로 바인딩에 .on() 메서드를 사용하는 것이 좋습니다.

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

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

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 개발자 도구 프로필을 사용하여 페이지 로딩 시간을 테스트합니다.

일반 제본(그렇게 부르자)

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

제본 진행 시간

2013-08-13_190358

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

.on() 바인딩

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

제본 진행 시간

2013-08-13_191010

.on() 바인딩은 이벤트 프록시를 사용하며 문서에 클릭 이벤트만 등록합니다. 메모리 사용량은 약 2.2M이고 바인딩 시간은 약 1ms입니다.

위 내용은 이 글의 전체 내용입니다. jquery on() 메소드를 배우는 모든 분들에게 도움이 되었으면 좋겠습니다.

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