Reputation: 282
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?
Upvotes: 2
Views: 770
Reputation: 121
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.
Upvotes: 0
Reputation: 26732
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"
});
Upvotes: 3