jqueryzepto

jQuery event.target with <a> and <p> tags


I have a jQuery event for all <a> tags set up like this

$('a').live('click', function(event)

and I am getting the href of the tag using this

var href = event.target.href;

Here is my HTML:

<a href="/test/path/">
     <p>My Link</p>
</a>

I can successfully log var href in the console when I click in the area of the <a> tag, but when I click on the text (the <p> tag within the <a> tag), my console says 'undefined' for event.target.href and '[object HTMLParagraphElement]' for event.target.

How can I check if the user is clicking on the text and get the href value of the <a> tag it is child of?


Solution

  • Get your href value like this

    $('a').live('click', function(){
      var target=$(this).attr("href");
      alert(target);
    });
    

    JsFiddle Sample http://jsfiddle.net/Gz6mT/7/

    If you are using jQuery 1.7+, Use .on() to attach event handlers insted of live. live() is deprecated as of jQuery 1.7

    http://api.jquery.com/on/