Search code examples
jqueryevent-handlingtargeting

jQuery .on() is giving me the wrong "this"


Probably a slap-my-forehead solution, but:

<div id="foo">
   <!-- this will all be replaced periodically via AJAX -->
   <p id="bar_1">click me</p>
   <p id="bar_2">click me</p>
   <p id="bar_3">click me</p>
   <!-- end AJAXed section -->
</div>

$('#foo').on(click,'p',function(){
   alert($(this).attr('id'));
   //returns "foo"
});

Clicking any p alerts "foo". How do I return "bar_n", the id of the p that was clicked?

I'm targeting the outer div because it's reliable and not going to be replaced via AJAX. Within the .on() method, I'm targeting (subtargeting?) the inner p because that's what I really want to bind the click handler to. All the p's will be replaced periodically, and their bindings lost, therefore, I can't simply say $('p').on(click...). Can I?


Solution

  • You need to add quote here click like - 'click' and every thing will be fine then, fiddle already submitted by @Arun.

    Try this -

    $('#foo').on('click','p',function(){
       alert($(this).attr('id'));
       //returns "foo"
    });