Reputation: 870
I have the following jQuery code:
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
jQuery('a.connect').bind("click", function(event)
{
var str = event.target.id;
alert (str);
var uid = str.substring(str.indexOf("_") + 1);
//connect (uid);
});
});
</script>
When I use the following HTML
<a class="connect button-small-blue" id="connect_{$uid}" href="#">Connect</a>
everything works great. However, when I use
<a class="connect" id="connect_{$uid}" href="#"><img src="{$imgSocialConnect}" alt="{$lblSocialConnect}" title="{$lblSocialConnect}" /></a>
The alert(str) call comes up empty.
I just figured out that when I replace the alert call with
alert (jQuery(this).attr('id') );
the ID is retrieved correctly.
Can anybody shine some light on this and tell me what's going on why the 2nd HTML variant is not working with the jQuery function as it is now?
Upvotes: 3
Views: 293
Reputation: 50573
That's because when you click in the second variant case, you are really clicking in the image, the click event then propagates to the enclosing a
element, so when you print the event.target.id
you are trying to access the id
of the image, which does not exist, and so you get an empty string.
You can test by doing this in your second variant case:
alert(event.target.tagName);
that should give you IMG .
To access the id
of the a
element in the second variant case, just do $(this).attr('id')
Upvotes: 3