简体   繁体   中英

Jquery delegation on jquery collection/domRef but selector string

I have a scenario where I have actual dom reference to dom element and want to delegate event to that dom reference.

var domRef = $('.selector');
// I want something like this.
$(document).on('click', domRef, function() {

});

I know it makes no sense to use it this way in the above code but I have a used case for myself where I want such functionality. I would appreciate can provide me solution without debating on the reason for following such practice.

Just handle the delegation manually:

var domRef = $('.selector');

$(document).on('click', function(e) {
    // test if the click target is the same as your domRef
    if ($(e.target).is(domRef)) {
        // do special stuff for this node
    }
});

From the documentation of .on() .

.on( events [, selector] [, data], handler(eventObject) )

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 is always triggered when it reaches the selected element.

The selector needs to be a string. If it is not then it is considered to be the parameter data . You can confirm this by looking at .on() 's source code.

A workaround may be doing something like:

var $domRef = $('.selector');

$(document).on('click', function(evt) {
  if($domRef.is(evt.target)) {
    ...
  }
});

Even though, performance-wise it is not so good.

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