JQuery delegate object instead of selector as first argument

Is it possible to pass an object instead of a selector as the first argument to a jQuery delegate?

var ancestor = $('ancestor'), children = ancestor.find('a'); ancestor.delegate(children, eventType, handler); 

Instead of regular:

 ancestor.delegate('a', eventType, handler); 

EDIT

Motivation:

 var children = $('a[href^="#"]').map($.proxy(function(i, current) { var href = $(current).attr('href'); if(href.length > 1 && givenElement.find(href).length === 1) return $(current); }, this)); $(document).delegate(children, eventType, handler); 

I want to delegate only anchor elements, which are the hash associated with any element as a child of this element. Basically, I want to do what you cannot do with just the selector.

+4
source share
1 answer

You can always simply configure delegation and then make your predicate inside the event handler:

 ancestor.delegate('a[href^="#"]', 'click', function(ev) { if (someElement.find($(ev.target).attr('href')).length > 0) { // do whatever with ev.target } }); 

If you want to avoid price while doing this jQuery DOM search inside the handler, you can pre-tag all the โ€œgoodโ€ tags:

 $('a[href^="#"]').each(function() { if (someElement.find($(this).attr('href')).length > 0) $(this).addClass("special"); }); 

Then your delegated event handler can just check

  if ($(ev.target).hasClass('special')) { // do stuff } 

which will work well enough not to be a problem under any circumstances.

The reason you should start with the selector for ".delegate ()" is because it has implemented. An event handler always does something like:

  function genericDelegateHandler(ev) { if ($(ev.target).is(theSelector)) { userHandler.call(this, ev); } } 

Now, obviously, he can also try to compare the actual elements if you configured the delegate without a selector, but he just doesnโ€™t.

edit - @DADU (OP) correctly indicates that if you encounter the problem of marking everything with the class name, then you donโ€™t even need an event handler that tests; the usual ".delegate ()" will do this. :-)

+2
source

All Articles