简体   繁体   中英

Date-picker Next click event

I needed to preform a event for the next button on the jQuery date-picker and got what I needed from this answer:

jquery datepicker adding event to next and previous button

But what I don't understand is why:

$(document).on('click', '.ui-datepicker-next', function() {
  // Preform event
};

Works but:

$(".ui-datepicker-next").on('click', function() {
  // Preform event
};

Doesn't work, in my case after two clicks?

This is called event delegation , and it is used when items are added to the DOM after the DOM has already been rendered.

The problem is that the click event is not bound to the desired element, because that element will later be injected into the DOM, so it does not yet exist. So jQuery must bind the click event to an element that actually exists at the time the DOM is rendered, and use event delegation (bubbling) to trap the event once the element is injected into the DOM.

Therefore, you need not use $(document) as your anchor, but you do need to use an element that is present when the DOM is rendered.

However, it is helpful to begin by using $(document).on and getting the code working, and then (once working) you can further narrow down the element you will use to trap the event.

Further reading:

https://davidwalsh.name/event-delegate

https://learn.jquery.com/events/event-delegation/

From the jQuery API docs :

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

In the first case, the handler is attached to the document which is guaranteed to be present. The selector then ensures the handler is only triggered when you click on .ui-datepicker-next .

However, in the second, there is no object available to attach the handler to, because the .ui-datepicker-next isn't present in the DOM at the time the handler is registered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM