SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Wizard tgavin's Avatar
    Join Date
    Feb 2003
    Location
    FL
    Posts
    1,051
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    passing variables from a link

    Code HTML4Strict:
    <a href="#" class="foo" data-email="test@test.com">test 1</a><br>
    <a href="#" class="foo" data-email="me@email.com">test 2</a>
     
    <script>
        $(document).ready(function(){
            $('.foo').click(function() {
            var email = $('.foo').attr('data-email');
            alert(email);
        });
    });
    </script>

    I'm trying to pass the value of data-email to my script, and as you javascript guys know, this isn't working correctly. How can I do this?

    Thanks!

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,892
    Mentioned
    211 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    This isn't hard. Use $(this) which in the context of your event handler will always refer to the element that recieved the click.

    Code JavaScript:
    $(document).ready(function(){
      $('.foo').click(function() {
        var email = $(this).data('email');
        console.log(email);
      });
    });

    Also, don't write $('.foo').attr('data-email'), use jQuery's data API instead: $(this).data('email');

  3. #3
    SitePoint Wizard tgavin's Avatar
    Join Date
    Feb 2003
    Location
    FL
    Posts
    1,051
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •