Syntax for using the selector in the .on () method of event-map?

I am trying to create a .on () method using event-map. I want to change this: $("ul").on("click", "li", function() {...}); on something like this:

 $("ul").on({ click: function() {...}, mouseenter: function() {...}, mouseleave: function() {...} }); 

Where can I put the "li" selector in the event map?

+4
source share
3 answers

You just put it as the second argument, as usual:

 $("ul").on ( { click: function() { ... }, mouseenter: function() { ... }, mouseleave: function() { ... } }, 'li' ); 

From the docs :

.on (event-map [, selector] [, data])

events-map A map in which string keys represent one or more events, separated by spaces of types and additional namespaces, and values ​​represent a handler function that must be called for event (s).

selector A selector string to filter the descendants of the selected elements that will invoke the handler. If the selector is null or omitted, the handler is always called when it reaches the selected item.

data strong> Data passed to the handler in event.data when an event occurs.

Parameters enclosed in [] are optional. So, if you don’t pass the selector, the events are bound to the elements in the jQuery object, in this case all the ul elements on the page. If, however, a selector is provided, then elements in jQuery objects handle event delegation for a set of elements matching the selector. I. When an event occurs on an element corresponding to a selector that is a descendant of the element in the jQuery object, this event handler will be called after the event fires before the parent. Note that this means that if the event propagation is canceled before it reaches the parent, the event handler will not be called.

+10
source

After map events:

 $("ul").on ({ click: function() { ... }, mouseenter: function() { ... }, mouseleave: function() { ... } }, "li"); 

Example: http://jsfiddle.net/pPPW4/

In docs :

.on (event-map [, selector] [, data])

+3
source

After the event map:

 $("ul").on ({ click: function() { ... }, mouseenter: function() { ... }, mouseleave: function() { ... } }, 'li'); 

From the documentation :

.on (event-map [, selector] [, data])

+2
source

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


All Articles