click () 대신 jQuery on ()을 사용하는 이유
현재 jQuery를 사용하면 클릭이 발생할 때 뭔가를해야 할 때 이렇게 할 것입니다.
$(".close-box").click( function() {
MoneyBox.closeBox();
return false;
});
다른 사람이 프로젝트에 가지고있는 코드를보고 있었는데 이렇게합니다.
$(".close-box").live("click", function () {
MoneyBox.closeBox();
return false;
});
지금은 Deprecated이고 jQuery 문서가 on()
대신 사용하라고 말하는 live () 함수를 사용 하고 있지만 첫 번째 예제 대신 live / on ()을 사용하는 이유는 무엇입니까?
동적으로 생성 된 요소 (예 : AJAX 호출에서 발생)가있을 수 있으므로 이전에 동일한 요소 선택기에 바인드 된 동일한 클릭 핸들러를 갖고 싶을 수 있습니다. 그런 다음 on()
with selector 인수를 사용하여 클릭 이벤트를 "위임"합니다.
시연하려면 :
on()
click()
선택기를 지정하지 않은 경우 다음 과 동의어 일 수도 있습니다 .
$('.elementClass').click(function() { // code
});
와 동의어이다
$('.elementClass').on('click', function() { // code
});
클래스가있는 모든 요소에 핸들러를 한 번만 추가한다는 의미에서 elementClass
. 새가있는 경우 elementClass
, 예를 들어,에서 오는 $('<div class="elementClass" />')
, 핸들러가 그 새로운 요소에 구속되지 않습니다, 당신은 할 필요가 :
$('#container').on('click', '.elementClass', function() { // code
});
가정 #container
되는 .elementClass
의 조상
많은 답변이 있으며 각각 몇 가지 요점을 다룹니다. 이것이 무엇인지, 어떻게 사용하는지에 대한 좋은 설명과 함께 여러분의 답변을 제공 할 수 있기를 바랍니다.
를 사용하는 click()
것은의 별칭 bind('click' ...)
입니다. 를 사용 bind()
하면 이벤트 리스너가 설정 될 때 DOM을 그대로 사용 하고 DOM에서 일치하는 각 요소에 함수를 바인딩합니다. 즉, 사용 $('a').click(...)
하면 해당 코드가 실행될 때 찾은 DOM의 모든 앵커 태그의 클릭 이벤트에 제공된 함수를 바인딩하게됩니다.
사용 live()
은 jQuery에서 옛날 방식이었습니다. 이벤트를 바인딩하는 데 사용 된 것처럼 bind()
코드가 실행될 때 DOM의 요소에 바인딩하는 것이 아니라 DOM의 변경 사항을 수신하고 이벤트를 향후 일치하는 요소에도 바인딩합니다. 이것은 DOM 조작을하고 있고 나중에 DOM에 제거 / 업데이트 / 추가 될 수 있지만 DOM이 처음로드 될 때 존재하지 않는 일부 요소에 이벤트가 존재해야하는 경우에 유용합니다.
live()
현재 감가 상각 된 이유 는 제대로 구현되지 않았기 때문입니다. 를 사용 live()
하려면 처음에 DOM에서 하나 이상의 요소를 선택할 수 있어야했습니다 (내 생각에). 또한 함수의 복사본이 각 요소에 바인딩되도록 실행되었습니다. 1000 개의 요소가있는 경우 많은 복사 된 함수입니다.
on()
기능 의 생성은 이러한 문제를 극복하는 것이 었습니다. 단일 이벤트 리스너를 DOM에서 변경되지 않는 객체에 바인딩 할 수 있으므로on()
나중에 DOM에서 제거 / 추가 될 요소 -부모 객체에 바인딩). 선택자와 일치하는 요소로 버블 링 될 때만 함수가 실행되도록하는 요소 "필터". 즉, 단일 요소에 바인딩 된 하나의 함수 (복사본이 아님) 만 있음을 의미합니다. DOM에 "라이브"이벤트를 추가하는 훨씬 더 나은 접근 방식입니다.
... 그리고 그것이 차이점이 무엇이며 각 기능이 존재하는 이유 live()
와 감가 상각 이유 입니다.
$("a").live()
-><a>
호출 후 생성 되더라도 모든에게 적용됩니다 .$("a").click()
-> 이것이<a>
호출되기 전에 모든 사람에게만 적용됩니다 . (이것은bind()
, 및on()
1.7 의 바로 가기입니다 )$("a").on()
-> 이벤트 핸들러 연결에 필요한 모든 기능을 제공합니다. (jQuery 1.7의 최신 버전)
인용구 :
jQuery 1.7부터 .live () 메서드는 더 이상 사용되지 않습니다. .on ()을 사용하여 이벤트 핸들러를 첨부하십시오. 이전 버전의 jQuery 사용자는 .live ()보다 .delegate ()를 우선적으로 사용해야합니다.
이 메서드는 페이지의 문서 요소에 위임 된 이벤트 처리기를 연결하는 수단을 제공하여 콘텐츠가 페이지에 동적으로 추가 될 때 이벤트 처리기 사용을 단순화합니다. 자세한 내용은 .on () 메서드에서 직접 대 위임 된 이벤트에 대한 설명을 참조하십시오.
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.
For earlier versions, the .bind() method is used for attaching an event handler directly to elements.
click()
is a shortcut to the non delegation method of on()
. So:
$(".close-box").click() === $(".close-box").on('click')
To delegate events with on()
, ie. in dynamic created objects you can do:
$(document).on('click', '.close-box') // Same as $('.close-box').live()
But, on()
introduces delegation in any static element, not just document
as live()
does, so:
$("#closestStaticElement").on('click', '.close-box')
You should read up on the difference between live
and bind
.
In a nutshell, live
uses event delegation, allowing you to bind to elements that exist now and in the future.
In contrast, handlers attached via bind
(and its shortcuts, like click
) attach handlers directly to the DOM elements matching the selector, and therefore are only bound to elements that exist now.
A consequence of live
's flexibility is decreased performance, so only use it when you need the functionality it provides.
$el.click(fn)
is a shortcut for $el.on('click', fn)
See http://api.jquery.com/click/ and http://api.jquery.com/on/ for more info.
When you need to bind some event handlers to dynamically added elements
you have to use live
(deprecated) or on
make the it working. Simply $('element').click(...);
won't work on any dynamically added element in to the DOM.
More on The Difference Between jQuery’s .bind(), .live(), and .delegate().
$.click() is merely a shortcut for either bind or on. From jQuery docs:
In the first two variations, this method is a shortcut for .bind("click", handler), as well as for .on("click", handler) as of jQuery 1.7. In the third variation, when .click() is called without arguments, it is a shortcut for .trigger("click").
The .on()
method attaches event handlers to the currently selected set of elements in the jQuery object. The click()
method binds an event handler to the "click" JavaScript event, or triggers that event on an element.
In the plain .click(...
if the target of the selector changes on the fly (e.g via some ajax response) then you'd need to assign the behavior again.
The .on(...
is very new (jQuery 1.7) and it can cover the live scenario using delegated events which is a faster way to attach behavior anyway.
In on
method, event handler is attached to the parent element instead of target.
example: $(document).on("click", ".className", function(){});
In above example, click event handler is attached to document. And it uses event bubbling to know whether someone clicked on the target element.
참고URL : https://stackoverflow.com/questions/10082031/why-use-jquery-on-instead-of-click
'Programing' 카테고리의 다른 글
클릭시 확인 대화 상자-AngularJS (0) | 2020.09.18 |
---|---|
AWS CLI 도구에서 AWS 계정 번호를 얻는 빠른 방법은 무엇입니까? (0) | 2020.09.18 |
pandas.DataFrame을 뒤집는 올바른 방법? (0) | 2020.09.18 |
ProcessBuilder : 기본 스레드를 차단하지 않고 시작된 프로세스의 stdout 및 stderr 전달 (0) | 2020.09.18 |
Javascript의 MSIE 및 addEventListener 문제? (0) | 2020.09.18 |