JQuery on () docs

Are the docs for the jQuery on() function incorrect (or obscure)? Consider this code:

 <div> <span> <div> <input type="button" value="click me!" /> </div> </span> </div> $(document).on("click", function() { console.log(this.toString()); }); 

Status of documents

selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event always fires when it reaches the selected item.

Pressing a button calls only one console.log for the document itself, and $(document).on("click", "*", function()... calls a lot.

I know that the community is not responsible for jQuery docs, but shouldnโ€™t it be said that when the selector is disabled, the event fires only when it reaches the selected element? Or is there something about delegation, I donโ€™t get it right?

Complete the violin

+4
source share
2 answers

When exiting the selector, there is no event delegation. From the docs:

If the selector is omitted or equal to zero, the event handler is called direct or direct. A handler is called every time an event occurs on selected elements, regardless of whether it happens directly on an element or bubbles from a streaming (internal) element.

When a selector is provided, the event handler is called delegated. The handler is not called when the event occurs directly on the associated element, but only for descendants (internal elements) that match the selector. jQuery bubbles an event from the target event to the element in which the handler is attached (that is, the outermost element) and fires the handler for any elements along this path corresponding to the selector.

Basically .on does jQuery - it is overloaded to do completely different things depending on the arguments. Personally, I prefer .delegate for delegation and .bind for regular events, since they are much clearer, and I hope that they will not be removed in later versions.

+4
source

Personally, I think this is clear enough. When the selector is omitted, the event is fired when it reaches the selected item. The word "always" in my opinion does not change the meaning. The event will always fire when it reaches the selected element (note that if something like stopPropagation , the event will not reach the selected element and therefore will not be fired).

When a selector is present, the event is fired when it reaches the selected element that has arisen from the element corresponding to the selector.

When you use the universal selector * , each individual element between the target and the selected element triggers an event.

As you pointed out in your comment, on provides all the functions needed to bind events in jQuery 1.7 +:

As in jQuery 1.7, the .on () method provides all the necessary functionality for attaching event handlers.

+4
source

Source: https://habr.com/ru/post/1389695/


All Articles