Programming

jQuery`click`,`bind`,`live`,`delegate`,`trigger` 및`on` 함수의 차이점은 무엇입니까?

procodes 2020. 6. 21. 20:48
반응형

jQuery`click`,`bind`,`live`,`delegate`,`trigger` 및`on` 함수의 차이점은 무엇입니까?


에 대한 각 함수의 설명서를 읽었 jQuery official website지만 아래 함수 사이에는 비교 목록이 없습니다.

$().click(fn)
$().bind('click',fn)
$().live('click',fn)
$().delegate(selector, 'click', fn)
$().trigger('click') // UPDATED
$().on('click', selector ,fn); // more UPDATED

참조 링크를 피하십시오.

위의 모든 기능은 어떻게 작동하며 어떤 상황에서 어떤 기능을 선호해야합니까?

참고 : 동일한 기능 또는 메커니즘을 가진 다른 기능이있는 경우 자세히 설명하십시오.

최신 정보

나는 또한 $.trigger기능을 보았다 . 위의 기능과 유사하게 작동합니까?

추가 업데이트

이제 v1.7에.on 추가 되었으며이 기능이 위의 모든 기능 요구 사항을 함께 다루고 있다고 생각합니다.


페이지 를 읽기 전에 다른 페이지에서이 이벤트 목록을 가져 오면 API 자체가 매우 유용하며 아래에서 논의하는 모든 내용이이 페이지에서 직접 연결됩니다 .

먼저 .click(function)말 그대로 바로 가기입니다 .bind('click', function). 다음 과 같이 핸들러 를 요소에 직접 바인딩 할 때 사용하십시오 .

$(document).click(function() {
  alert("You clicked somewhere in the page, it bubbled to document");
});

이 요소가 교체되거나 폐기되면이 핸들러는 더 이상 존재하지 않습니다. 또한 핸들러를 연결하기 위해이 코드를 실행할 때 존재하지 않은 요소 (예 : 선택기가 발견 한 요소)는 핸들러를 얻지 못합니다.

.live().delegate()유사하게 관련되어 .delegate()실제로 사용 .live()둘 다 거품으로 이벤트를 수신, 내부적으로. 이것은 새로운 요소와 오래된 요소 에서 작동 하며 동일한 방식으로 이벤트를 버블 링합니다. 요소가 변경 될 때 (예 : 새 행, 목록 항목 추가 등) 사용할 수 있습니다. 페이지에 남아 있고 어느 시점에서도 교체되지 않는 부모 / 공통 조상이없는 경우 다음과 같이을 사용 .live()하십시오.

$(".clickAlert").live('click', function() {
  alert("A click happened");
});

그러나 대체되지 않는 어딘가에 부모 요소가있는 경우 (이벤트 핸들러는 안녕히 가십시오) 다음과 .delegate()같이 처리해야 합니다.

$("#commonParent").delegate('.clickAlert', 'click', function() {
  alert("A click happened, it was captured at #commonParent and this alert ran");
});

이것은와 거의 동일하게 작동 .live()하지만 캡처 및 처리기가 실행되기 전에 이벤트 버블 링 횟수가 줄어 듭니다. 이 두 가지의 또 다른 일반적인 용도는 요소에서 클래스가 변경되어 더 이상 원래 사용했던 선택기와 일치하지 않는다는 것입니다. 이러한 메소드를 사용 하면 이벤트 가 발생했을 선택기가 평가 됩니다 ( 일치하는 경우 핸들러 실행). . 따라서 요소가 더 이상 선택기와 일치하지 않아 더 이상 실행되지 않습니다. .click()하지만, 이벤트 처리기가 DOM 요소에 바인딩 된 권리이며, 그것을 찾는 데 사용 된 어떤 선택 일치하지 않는다는 사실은 무관하다 ... 이벤트가 바인딩하고 해당 요소가 사라 때까지 머물고, 또는 핸들러 를 통해 제거됩니다 .unbind().

그러나 또 다른 일반적인 사용 .live()하고 .delegate()있다 성능 . 많은 요소를 다루는 경우 각 요소에 직접 클릭 핸들러를 연결하면 많은 비용과 시간이 소요됩니다. 이 경우 단일 핸들러 를 설정하고 버블 링 작업을 수행하는 것이 더 경제적입니다 .이 질문에 큰 차이가있는 부분을 살펴보십시오 . 응용 프로그램의 좋은 예입니다.


트리거링 -업데이트 된 질문

가능 2 메인 이벤트 핸들러 트리거 기능이있다, 그들은 API에서 동일한 "이벤트 핸들러 첨부 파일"범주에 속하는 이들이다 .trigger().triggerHandler(). .trigger('eventName')일반적인 이벤트에 대한 바로 가기가 내장되어 있습니다 (예 :

$().click(fn); //binds an event handler to the click event
$().click();   //fires all click event handlers for this element, in order bound

바로 가기를 포함한 목록을 여기에서 볼 수 있습니다 .

차이점에 .trigger()대해서는 이벤트 핸들러를 트리거합니다 (그러나 대부분의 경우 기본 조치는 <textarea>아님). 이벤트 핸들러가 바인드 된 순서대로 (네이티브 이벤트와 동일하게), 네이티브 이벤트 조치를 발생시키고 DOM을 버블 링합니다.

.triggerHandler()일반적으로 다른 목적으로 사용됩니다. 여기서는 바인딩 된 핸들러를 시작하려고합니다. 예를 들어 양식 제출과 같은 기본 이벤트가 실행되지 않습니다. DOM을 버블 링하지 않고 체인화 할 수 없습니다 (해당 이벤트에 대한 마지막 바인딩 이벤트 핸들러가 반환하는 것을 반환합니다). 예를 들어, focus이벤트 를 트리거하고 싶지만 실제로 객체에 초점을 맞추고 싶지 않다면 바인딩하려는 코드 .focus(fn)를 실행 하고 싶을 것입니다. 그렇지만 실제로 .trigger()요소에 초점을 맞추고 버블 업하는 것입니다.

실제 예는 다음과 같습니다.

$("form").submit(); //actually calling `.trigger('submit');`

This would run any submit handlers, for example the jQuery validation plugin, then try to submit the <form>. However if you just wanted to validate, since it's hooked up via a submit event handler, but not submit the <form> afterwards, you could use .triggerHandler('submit'), like this:

$("form").triggerHandler('submit');

The plugin prevents the handler from submitting the form by bombing out if the validation check doesn't pass, but with this method we don't care what it does. Whether it aborted or not we're not trying to submit the form, we just wanted to trigger it to re-validate and do nothing else. (Disclaimer: This is a superfluous example since there's a .validate() method in the plugin, but it's a decent illustration of intent)


The first two are equivalent.

// The following two statements do the same thing:
$("blah").click( function() { alert( "Click!" ); } );
$("blah").bind( "click", function() { alert( "Click!" ); } ); 

The second one, though, can be used to bind to more than one event at the same time, by specifying several space-separated event names:

$("blah").bind( "click mouseover mouseout", function() { alert( "Click! Or maybe mouse moved." ); } ); 

The .live method is more interesting. Consider the following example:

<a class="myLink">A link!</a>
<a id="another">Another link!</a>

<script>
    $("a.myLink").click( function() { alert( 'Click!' ); } );

    $("a#another").addClass( "myLink" );
</script>

After the second line of the script executes, the second link will also have a CSS class of "myLink". But it will not have the event handler, because it didn't have the class when the event was attached.

Now consider you wanted it to be the other way around: every time a link with class "myLink" appears somewhere on the page, you want it to have the same event handler automatically. This is very common when you have some kind of lists or tables, where you add rows or cells dynamically, but want them all to behave in the same way. Instead of going to all the pain of assigning event handlers anew every time, you can use the .live method:

<a class="myLink">A link!</a>
<a id="another">Another link!</a>

<script>
    $("a.myLink").live( "click", function() { alert( 'Click!' ); } );

    $("a#another").addClass( "myLink" );
</script>

In this example, the second link will also get the event handler as soon as it gets the "myLink" class. Magic! :-)

Of course, it's not that literal. What .live really does is attach the handler not to the specified element itself, but to the very root of the HTML tree (the "body" element). Events in DHTML have this funny feature of "bubbling up". Consider this:

<div> <a> <b>text</b> </a> </div>

If you click on "text", then first the <b> element will get a "click" event. After that, the <a> element will get a "click" event. And after that the <div> element will get a "click" event. And so on - all the way up to the <body> element. And that's where jQuery will catch the event and see if there are any "live" handlers which apply to the element that caused the event in the first place. Neat!

And finally, the .delegate method. It simply takes all the children of your element that conform to the given selector and attach a "live" handler to them. Take a look:

$("table").delegate( "td", "click", function() { alert( "Click!" ); } );

// Is equivalent to:
$("table").each( function() {
    $(this).find( "td" ).live( "click", function() { alert( "Click!" ); } );
} );

Questions?


As of jQuery 1.7, the .live() method was deprecated. If you are using a jQuery version < 1.7 than it is officially recommended to use .delegate() over .live().

.live() has now been replace with .on().

Best to go directly to the jQuery site for more information, but here are the current versions of the .on() method:

.on( events [, selector] [, data], handler(eventObject) )
.on( events-map [, selector] [, data] )

http://api.jquery.com/on/


$().click(fn) and $().bind('click', fn) are identical at first sight, but the $.bind version is more powerful for two reasons:

  1. $().bind() allows you to assign one handler to multiple events, for example, $().bind('click keyup', fn).
  2. $().bind() supports namespaced events - a powerful feature if you want to remove (unbind) only certain event handlers that an element is bound to - read more in Namespaced Events.

Live vs delegate: this has already been answered in the other replies.


This is where reading the API might help. However, I know off the top of my head, so you can continue being lazy (yay!).

$('#something').click(fn);
$('#something').bind('click',fn);

There's no difference here (that I know of). .click is simply a convenience/helper method to .bind('click'

// even after this is called, all <a>s in
// <div class="dynamic_els"> will continue
// to be assigned these event handlers

$('div.dynamic_els a').live(‘click’,fn);

This is very different, as .live adds events to the selector you pass in (which you haven't here) and continues to look at the DOM as nodes are inserted / removed

$('#some_element').delegate('td','click',fn);

This is only different because of the way you're assigning event handlers. .delegate is centered on DOM event bubbling. The basic principle is that every event bubbles upward through the DOM tree until it reaches the root element (document or window or <html> or <body>, I can't remember exactly).

Either way, you're binding an onclick handler to a all the <td>s within $('#some_element') (you must specify a selector, though you could say $(document)). When one of its children is clicked, the event bubbles up to the <td>. You can then extract the source element of the event (which jQuery does for you automagically).

This is useful when there are tons of elements and you only have only a few (or one central) point[s] that these events will go through. This saves the browser effort and memory to consolidate these event handlers into less objects.

참고URL : https://stackoverflow.com/questions/2954932/difference-between-jquery-click-bind-live-delegate-trigger-and-on

반응형