Question

I'm using jQuery's .on() with a selector to delegate to a filtered set of descendants, like this:

selectedElement.on("click", "[data-click]", clickHandler);

In this case, binding the clickHandler function to a click event on any descendant that has a "data-click" attribute (with any value).

If selectedElement itself has a "data-click" attribute, it is not bound. I can't use the selected element's parent instead, because it contains other children that I don't want bound. This bind is occurring inside a function that receives selectedElement as an argument, so I have no advance knowledge of what kind of element it is or what selector I would use to select it. I would prefer not to have to bind the selected element separately.

Is there a way to include the selected element itself in the set which is filtered and bound by .on?

Was it helpful?

Solution

Like @Joseph Silber said, you can't really do that. Here is what I would do in a similar situation:

selectedElement.on('click', function(ev) {
    // Alternatively, you could do $(this).is('[data-click]')
    if ( ev.target.hasAttribute('data-click') ) {
        clickHandler(ev);
    }
});

That way you can still use your clickHandler variable if that's what you're doing.

OTHER TIPS

I would just bind them separately, but if you insist, you can bind them to the parent and modify your selector to only include either the container itself, or one of its descendants:

var selector = '.container[data-click], .container [data-click]';

$('.parent').on('click', selector, clickHandler);

Here's the fiddle: http://jsfiddle.net/e4tDL/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top