2

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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
anthony
  • 282
  • 1
  • 3
  • 14

2 Answers2

3

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"
});
BenMorel
  • 34,448
  • 50
  • 182
  • 322
swapnesh
  • 26,318
  • 22
  • 94
  • 126
  • 1
    That absolutely does work. [head slap!] Unfortunately, in my more complex real world code, I can't seem to make the `$(this)` call work. I'll see if I can more accurately reproduce the problem next time... Thank you. – anthony Aug 08 '13 at 04:30
  • If you care to take a look... I was able to reproduce my actual problem in pseudo code: [jsfiddle](http://jsfiddle.net/guMjh) I'm only getting "foo" on the alerts. – anthony Aug 08 '13 at 04:45
  • 1
    @anthony: `$('#foo').on('click','p', ...` not `$('#foo').on('click',$p, ...` – Kabie Aug 08 '13 at 04:52
  • @anthony you applied `on` method on `foo` id so it is throwing this – swapnesh Aug 08 '13 at 04:52
  • @anthony with what Kabie suggested will prompt bar_1 this time – swapnesh Aug 08 '13 at 04:54
  • @anthony sorry my bad I edit the code and its giving me this..what Kabie suggested is good .. :) – swapnesh Aug 08 '13 at 04:55
  • @Kabie Thank you, that worked! My subtarget (that's what I'll call it) shouldn't have been the jQuery object `$('p')`, it should have been the selector string `p`! – anthony Aug 08 '13 at 05:20
0

Two solutions:

Replace

$('#foo').on('click','p',function(){

with

$('#foo p').on('click',function(){

(as mentioned before, you need quotes around click).

OR, replace

alert($(this).attr('id'));

with

alert($(event.target).attr('id'));

I can't guarantee the first method will play nice with the AJAX loads, but I believe the second method should work just fine.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user2663103
  • 121
  • 2