Skip to content Skip to sidebar Skip to footer

Jquery Event Delegation With .on (this Reference)

Where does this reference to in a delegated .on event? Example: $('#foo').on('click', $('.bar'), function() { console.log(this); }); In the example this will reference to #foo

Solution 1:

Change it to this...

$('#foo').on('click', '.bar', function() {
    console.log(this);
});

Now this will be the clicked .bar.

If you want a jQuery object then use $(this) as normal.

Edit

As per the change to question code, you'll need this...

$('#foo').on('click', '.bar a'), function() {
    console.log(this);
});

That simply extends the click event handler to links inside .bar elements that may not exist at document.ready.

Solution 2:

Two ways.

  1. Use a string selector, not a jQuery object, when calling .on():

    $('#foo').on('click', '#bar', function() {
        console.log(this); // #bar
    });
    
  2. Specify a parameter name for the jQuery normalised event object, and use its target property:

    $('#foo').on('click', $('#bar'), function(e) {
        console.log(this); // #fooconsole.log(e.target); // #bar
    });
    

EDIT: Ignore the second option. jQuery doesn't accept a jQuery object for the selector, and as a result simply ignores it. You will not be setting up event delegation, you'd instead just be setting a static click event handler on #foo, which works due to event propagation.

Solution 3:

An ID should be used once in a page. So you can add a class fooClass to your 5 elements and do :

$('.fooClass').onclick(function() {
  alert("my bar element: " + $(this));
});

and do what you want with $(this).

Post a Comment for "Jquery Event Delegation With .on (this Reference)"